selenium.common.exceptions.WebDriverException:消息:类型错误:node.ownerDocument 为空

时间:2021-07-19 05:02:03

标签: python selenium selenium-webdriver

我想了解此失败的原因以及我应该在脚本中修改哪些内容以解决此问题并能够提供所需的抓取。关注数据:

测试站点:

http://sports.williamhill.com/bet/pt/betlive/24

我正在尝试收集这些框中的链接:

enter image description here

find_element_by_xpath 是正确的,但是当我尝试运行脚本时,它返回错误:

selenium.common.exceptions.WebDriverException: Message: TypeError: node.ownerDocument is null

我在 Virtual Studio Code 中的脚本项目:

import time
import requests
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import json

url = "http://sports.williamhill.com/bet/pt/betlive/24"

option = Options()
option.headless = True
driver = webdriver.Firefox(options=option)

driver.get(url)

time.sleep(1)

element = driver.find_element_by_xpath("//tr[@class='rowLive']//a/@href")
html_content = element.get_attribute('outerHTML')

soup = BeautifulSoup(html_content, 'html.parser')
table = soup.find(name='href')

df_full = pd.read_html(str(table))[0]

importar = {}
importar['importando'] = df_full.to_dict('records')

print(importar['importando'])

driver.quit()

1 个答案:

答案 0 :(得分:0)

我猜您的错误是您在 find_element_by_xpath 行中使用了 find_elements_by_xpath 而不是 element = driver.find_element_by_xpath("//tr[@class='rowLive']//a/@href"),因此当您参与获取所有链接时,这实际上返回了一个元素。< br/> 所以目前 html_content 是单个元素的 HTML。
souptable 容器也是如此。