Python xpath-Indexer错误:选择带有路径的元素后,列表索引超出范围
我在尝试运行下面的代码(在此处找到)时遇到以下索引错误: 卡片=卡片[0]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
索引器:列表索引超出范围 既然我是一个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
-如果找不到元素,它将返回异常