【发布时间】:2025-12-11 16:30:01
【问题描述】:
我正在尝试通过在python 中使用selenium 从网站上的多个页面中抓取数据。该语法在第一页上运行并scrape 数据成功,但在第二页之后,它找不到点击按钮并停止抓取。我检查了网页的HTML codes,但第二页上的元素与第一页上的元素相同。我发现这个question 与同一问题有关。我认为问题是由于在更改DOM 后对按钮的引用丢失,但我仍然无法正确解决问题。我将不胜感激任何建议或解决方案。语法和结果如下:
browser = webdriver.Chrome(r"C:\Users\...\chromedriver.exe")
browser.get('https://fortune.com/global500/2019/walmart')
table = browser.find_element_by_css_selector('tbody')
data =[]
#Use For Loop for Index
i = 1
while True:
if i > 5:
break
try:
print("Scraping Page no. " + str(i))
i = i + 1
# Select rows in the table
for row in table.find_elements_by_css_selector('tr'):
cols = data.append([cell.text for cell in row.find_elements_by_css_selector('td')])
try:
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,'//span[@class="singlePagination__icon--2KbZn"]')))
time.sleep(10)
finally:
browser.find_element_by_xpath('//span[@class="singlePagination__icon--2KbZn"]').click()
except Exception as e:
print(e)
break
data1 = pd.DataFrame(data, columns=['Labels','Value'])
print(data1)
browser.close()
输出:
Scraping Page no. 1
Scraping Page no. 2
Message: stale element reference: element is not attached to the page document
(Session info: chrome=....)
Labels Value
0 (...) (...)
1 (...) (...)
【问题讨论】:
-
这个问题和this previous one of yours的唯一区别是单个链接的格式。
-
对不起,实际上是几个链接的格式。无论如何,它们实际上是相同的。
-
仅供参考,它是 scrape(和 scraper、scraped、scraping)不是废品
标签: python selenium selenium-webdriver web-scraping