python - 使用 Selenium + Python 循环链接并从结果页面中抓取数据
问题描述
我是 Selenium 的新手,需要抓取一个包含结构完全类似的链接列表的网站:
<a class="unique" href="...">
<i class="something"></i>
"Text - "
<span class="something">Text</span>
</a>
<a class="unique" href="...">
<i class="something"></i>
"Text - "
<span class="something">Text</span>
</a>
...
...
我需要单击循环内的此链接列表并从结果页面中抓取数据。到目前为止我所做的是:
lists = browser.find_elements_by_xpath("//a[@class='unique']")
for lis in lists:
print(lis.text)
lis.click()
time.sleep(4)
# Scrape data from this page (works fine).
browser.back()
time.sleep(4)
它适用于第一个循环,但是当第二个循环到达
print(lis.text)
它抛出一个错误说:
StaleElementReferenceException:消息:过时的元素引用:元素未附加到页面文档
我已经尝试过print (lists)
了,它给出了所有链接元素的列表,所以效果很好。当浏览器返回上一页时,就会出现问题。我尝试过延长时间并使用browser.get(...)
而不是,browser.back()
但错误仍然存在。我不明白为什么它不会打印lis.text
,因为列表仍然包含所有元素的列表。任何帮助将不胜感激。
解决方案
您正在尝试单击文本而不是启动链接。
并且单击每个链接,抓取数据并导航回来似乎也不是有效的,而是您可以将所有链接存储在某个列表中,然后您可以使用该driver.get('some link')
方法导航到每个链接,您可以抓取数据。为了避免一些异常,请尝试以下修改后的代码:
# Locate the anchor nodes first and load all the elements into some list
lists = browser.find_elements_by_xpath("//a[@class='unique']")
# Empty list for storing links
links = []
for lis in lists:
print(lis.get_attribute('href'))
# Fetch and store the links
links.append(lis.get_attribute('href'))
# Loop through all the links and launch one by one
for link in links:
browser.get(link)
# Scrape here
sleep(3)
或者,如果您想使用相同的逻辑,则可以使用 Fluent Wait 来避免一些异常,例如 StaleElementReferenceException,如下所示:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import *
wait = WebDriverWait(browser, 10, poll_frequency=1, ignored_exceptions=[StaleElementReferenceException])
element = wait.until(EC.element_to_be_clickable((By.XPATH, "xPath that you want to click")))
我希望它有帮助...
推荐阅读
- tensorflow - tf.nn.depth_to_space vs pixel_shuffle
- django - 获取两个日期之间的天数
- xml - XSL for removing or changing empty xmlns on xml document
- haskell - 递归列表内的列表
- reactjs - 带有 react-hook-form 的 FormControlLabel
- mysql - 如何在不修改主键 ID 的情况下向上或向下移动数据库表内容?
- python - 正则表达式解析python中的对话
- python - 尝试使用 Python 创建 1000 个随机文件夹 - os.makedirs()
- python - 能够为 NBA 每日领袖抓取网站数据。但是 MaxRetryError 的问题
- python-3.x - 如何打印 numpy.ndarray 的内容?