Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python xpath-Indexer错误:选择带有路径的元素后,列表索引超出范围_Python_Selenium_Xpath_Webdriver_Index Error - Fatal编程技术网

Python xpath-Indexer错误:选择带有路径的元素后,列表索引超出范围

Python xpath-Indexer错误:选择带有路径的元素后,列表索引超出范围,python,selenium,xpath,webdriver,index-error,Python,Selenium,Xpath,Webdriver,Index Error,我在尝试运行下面的代码(在此处找到)时遇到以下索引错误: 卡片=卡片[0] 索引器:列表索引超出范围 既然我是一个Python新手,你能帮我解决这个问题吗? 非常感谢 card = driver.find_elements_by_xpath('//div[@data-testid="tweet"]') card = cards[0] #function that collects tweets while scrolling; filters out sponsored t

我在尝试运行下面的代码(在此处找到)时遇到以下索引错误:

卡片=卡片[0]
索引器:列表索引超出范围

既然我是一个Python新手,你能帮我解决这个问题吗? 非常感谢

card = driver.find_elements_by_xpath('//div[@data-testid="tweet"]')
card = cards[0]

#function that collects tweets while scrolling; filters out sponsored tweets; saves tweets in Tuple
def get_tweet_data(card):
    # get username of the tweet
    username_tweet = card.find_element_by_xpath('.//span').text
    # get Twitter Handle
    handle_tweet = card.find_element_by_xpath('.//span[contains(text()."@")]').text

    # get date of post - if no date, then sponsored tweet - then do not return
    try:
        date_tweet = card.find_element_by_xpath('.//time').get_attribute('datetime')
    except NoSuchElementException:
        return
    # get Text of Tweet
    comment = card.find_element_by_xpath('.//div[2]/div[2]/div[1]').text
    responding = card.find_element_by_xpath('.//div[2]/div[2]/div[2]').text
    text_tweet = comment + responding
    # number of replies, retweets, likes
    reply_count = card.find_element_by_xpath('.//div[@data-testid="reply"]').text
    retweet_count = card.find_element_by_xpath('.//div[@data-testid="retweet"]').text
    like_count = card.find_element_by_xpath('.//div[@data-testid="like"]').text

    tweet = (username_tweet, handle_tweet, date_tweet, text_tweet, reply_count, retweet_count, like_count)
    return tweet

get_tweet_data(card)



这意味着
driver.find_elements\u by_xpath('//div[@data testid=“tweet”]”)
没有返回任何内容,即没有与xpath匹配的元素find_elements\u by_xpath()返回已找到元素的列表,或者如果找不到元素,则不返回已找到元素的列表。所以在这种情况下,您需要在从“卡”中获取项目之前检查“卡”的长度。例如:

cards = driver.find_elements_by_xpath('//div[@data-testid="tweet"]')
if len(cards) > 0:
    card = cards[0]
else:
    raise NoSuchElementException('No cards were found')
也许,如果您使用
驱动程序。通过\u xpath()查找\u元素\u
而不是
驱动程序。通过\u xpath()查找\u元素\u
-如果找不到元素,它将返回异常