网页抓取器无法单击分页按钮



我正在使用硒和壁虎驱动程序(在Firefox上(来抓取eBay。我的操作系统是 Ubuntu 16.04。

我只想点击下一步按钮!我做错了什么?我已经评论了两个不起作用的按钮分配实例......

# import libraries
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import pandas as pd 
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
# specify the url
urlpage = 'https://www.ebay.com/b/Nike-Athletic-Apparel-for-Women/185082/bn_648725?rt=nc&LH_Sold=1' 
print(urlpage)
# run firefox webdriver from executable path of your choice 
driver = webdriver.Firefox()
# get web page
driver.get(urlpage)

for page_num in range(0, 2):
parentElement = driver.find_element_by_class_name("s-item")
results = parentElement.find_elements_by_css_selector("*") # all children by CSS
#button = driver.find_elements_by_class_name('ebayui-pagination__control') # not working
#button = driver.find_elements_by_xpath('//html/body/div[3]/div[3]/div[4]/section[1]/div[2]/nav/a[2]/span/svg[2]/use') # not working
button.click()
print('Number of results', len(results))
for r in results:
print(r.text)
df = pd.DataFrame(results)
df.head()
df.to_csv('eBay_scrape.csv')
driver.quit()

收到的错误:

https://www.ebay.com/b/Nike-Athletic-Apparel-for-Women/185082/bn_648725?rt=nc&LH_Sold=1
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-2-58b4e0e554fc> in <module>
19     #results = parentElement.find_elements_by_tag_name("li") # not working...
20     #results = driver.find_elements_by_class_name("vip") # 50 results per page. But useless...
---> 21     button = driver.find_elements_by_class_name('ebayui-pagination__control')
22     #button = driver.find_elements_by_xpath('//html/body/div[3]/div[3]/div[4]/section[1]/div[2]/nav/a[2]/span/svg[2]/use')
IndexError: list index out of range

driver.find_elements_by_class_name('ebayui-pagination__control')返回一个列表

该页面上有 2 个带有该类的按钮 - 要检查,请在 Firefox 控制台中键入以下内容:$$('.ebayui-pagination__control')

所以你需要:button = driver.find_elements_by_class_name('ebayui-pagination__control')[1]获取第二个按钮。

第二种方法 (find_elements_by_xpath( 对于这么长的 xpath,看起来非常脆弱,只需要一个阵列在该路径中更改,即使您一开始让它工作,它也将不再工作。

您可以诱导WebDriverWaitelement_to_be_clickable并遵循xpath

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//a[@class='ebayui-pagination__control'][@rel='next']"))).click()

与其按代码单击下一页按钮,不如更新抓取网址。

如果您注意到,&_pgn=<page_number>会附加到后续页面的 url 字符串中。您可以简单地抓取页面并递增页码,直到没有剩余的有效页码。

最新更新