[英]List comprehension with Selenium elements in Python not working with tweets
我正在使用 Selenium 抓取 Twitter 頁面,我抓取的推文存儲在列表變量tweets
。 我可以正常遍歷它們並使用以下方法從中提取文本:
for tweet in tweets:
print(tweet.text)
但是,當我嘗試使用列表理解並做
[tweet.text for tweet in tweets]
我得到一個StaleElementReferenceException
StaleElementReferenceException: Message: The element reference of [object String] "b22c079f-684f-4d46-942b-d5dd69203728" is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
為什么會這樣?
很大程度上取決於您嘗試構建列表tweets 的方式。
理想情況下,要使用Selenium和python從所有推文中提取文本,您必須為visibility_of_all_elements_located()
引入WebDriverWait ,您可以使用以下任一定位器策略:
使用CSS_SELECTOR
和get_attribute("innerHTML")
:
print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "css_selector_of_tweets")))])
使用XPATH
和text屬性:
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "xpath_of_tweets")))])
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
鏈接到有用的文檔:
get_attribute()
方法Gets the given attribute or property of the element.
text
屬性返回The text of the element.
當您嘗試列表理解時,元素的狀態已更改。 所以在列表理解之前獲取 tweets 元素,如下所示。
tweets = driver.find_elements_by_xpath('YOUR_XPATH_HERE')
tweets_lists = [tweet.text for tweet in tweets]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.