我正在嘗試根據不同的關鍵字來抓取 twitter,我希望腳本一個一個地獲取單詞并每次清除搜索框以使用下一個,但我有一個問題
============================================
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from time import sleep
searchbox = driver.find_element_by_xpath('//input[@aria-label="Search query"]')
keywords = ['Dog','Cat','Fox']
for keyword in keywords:
searchbox.clear()
searchbox.send_keys(keyword)
searchbox.send_keys(Keys.RETURN)
sleep(10)
driver.find_element_by_link_text('Latest').click()
sleep(5)
data = []
tweet_ids = set()
Keywoed=keyword
last_position = driver.execute_script("return window.pageYOffset;")
scrolling = True
while scrolling:
page_info = driver.find_elements_by_xpath('//article[@data-testid="tweet"]')
for info in page_info:
tweet = get_tweet_data(info)
if tweet:
tweet_id = ','.join(map(str, tweet))
if tweet_id not in tweet_ids:
tweet_ids.add(tweet_id)
data.append(tweet)
scroll_attempt = 0
while True:
# check scroll position
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
sleep(5)
curr_position = driver.execute_script("return window.pageYOffset;")
if last_position == curr_position:
scroll_attempt = 1
if scroll_attempt >= 3:
scrolling = False
break
else:
sleep(5) # attempt another scroll
else:
last_position = curr_position
break
def get_tweet_data(info):
UserName = info.find_element_by_xpath('.//span').text
try:
handle = info.find_element_by_xpath('.//span[contains(text(), "@")]').text
except NoSuchElementException:
return
try:
date = info.find_element_by_xpath('.//time').get_attribute('datetime')
except NoSuchElementException:
return
try:
image_element = info.find_elements_by_css_selector('div[data-testid="tweetPhoto"]')
images = []
for image_div in image_element:
href = image_div.find_element_by_tag_name("img").get_attribute("src")
images.append(href)
except NoSuchElementException:
return
try:
comment = info.find_element_by_xpath('.//div[1]/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]').text
except NoSuchElementException:
return
retweet_cnt = info.find_element_by_xpath('.//div[@data-testid="retweet"]').text
like_cnt = info.find_element_by_xpath('.//div[@data-testid="like"]').text
tweet = (comment,UserName,handle,date,images,retweet_cnt, like_cnt)
return tweet
==================================================== ===========
使用 searchbox.clear() 沒有幫助,它給了我錯誤:
對于關鍵字中的關鍵字:
----> searchbox.clear()
searchbox.send_keys(keyword) def clear(self): """Clears the text if it's a text entry element."""---> self._execute(Command.CLEAR_ELEMENT)
def get_property(self, name):StaleElementReferenceException:訊息:過時元素參考:元素未附加到頁面檔案(會話資訊:chrome = 101.0.4951.54)
uj5u.com熱心網友回復:
您正在離開頁面 - 這使搜索框元素“過時”。這意味著您已離開頁面/搜索框元素在任何時間段內都不再可見。
要解決此問題,您必須加載包含 searchbox 元素的頁面,重新運行代碼以找到 searchbox 元素,然后運行代碼。
我建議做類似的事情:
keywords = ['Dog','Cat','Fox']
for keyword in keywords:
driver.get("page_with_searchbox_element")
searchbox = driver.find_element_by_xpath('//input[@aria-label="Search query"]')
searchbox.clear()
searchbox.send_keys(keyword)
# Continue the rest of the code here...
這將在每次嘗試時重新加載頁面,并且您不應再遇到過時元素例外。
uj5u.com熱心網友回復:
謝謝@Jeremy
在我理解問題并像這樣修復它之后,它可以完美運行:
keywords = ['Dog','Cat','Fox']
for keyword in keywords:
driver.get("https://twitter.com/search?q=" keyword "&src=typed_query&f=live")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/478015.html
