如何使用 Selenium (Python3) 获取 table 的所有项目?

How I can get all items of table with Selenium (Python3 )?

我想在 https://www.oddsportal.com/soccer/england/premier-league/wolves-newcastle-utd-nNNqedbR/ 页面上从 table 获取信息。

这是一个table,它会自动更改她的项目(mb with js,ajax)。

如果我写下面的代码,我会得到错误 'HtmlElement' object has no attribute 'find_element_by_xpath'

url = 'https://www.oddsportal.com/soccer/england/premier-league/wolves-newcastle-utd-nNNqedbR/'

options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(chrome_options=options)
driver.get(url)

html = lxml.html.fromstring(driver.page_source)
tbody = html.find_element_by_xpath('//*[@id="odds-data-table"]/div[1]/table/tbody')
trows = tbody.find_elements_by_tag_name("tr")

lxml(大概)是 lxml 库,因此您的 html 对象是它的一个实例。正如例外所说 - 它没有 find_element_by_xpath() 和 tag_name 方法,它们在 selenium 库中。

所以不要使用 html 对象,而是使用 driver:

tbody = driver.find_element_by_xpath('//*[@id="odds-data-table"]/div[1]/table/tbody')
trows = tbody.find_element_by_tag_name("tr")