seleniumWebDriver不返回Wikipedia表



我正试图拼凑一张包含美国所有总统选举结果的表格。要做到这一点,我想使用硒。我相信我试图抓取的表是由客户端站点脚本(javescript(执行的,因此在抓取站点之前,我试图注意特定标签的存在。[注:我试过直接用漂亮的汤刮页面,但一直得到"无"的回复]。

这是我的密码。

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
import pandas
#using selenium and shromedriver to extract the javascript wikipage 
scrape_options=Options()
scrape_options.add_argument('--headless')
driver=webdriver.Chrome(executable_path='web scraping master/chromedriver', options=scrape_options)
page_info=driver.get('https://en.wikipedia.org/wiki/United_States_presidential_election')

#waiting for the javascript to load

try:WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CLASS_NAME,"wikitable 
sortablejquetablesorter")))
finally:page=driver.page_source
soup=BeautifulSoup(page,'html.parser')
table=soup.find('table',{'class':'wikitable sortable jquery-tablesorter'})

该代码不会返回所需的结果,而只是返回一个

TimeoutExceptionerror 

不管我给它多少时间。

另请注意:当我更换线路时:

try:WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CLASS_NAME,"wikitable 
sortablejquetablesorter")))

带有:

try:WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CLASS_NAME,"wikitable")))

它返回我需要的表,但原始表中只有一半的数据。

我认为我的代码有问题,但我似乎无法理解问题所在。有人能帮我吗?我被困在这里太久了。

通过class_name查找元素只接受类名。它不支持多个类名,而是使用css selector

try:
WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.CSS_SELECTOR,".wikitable.sortable.jquery-tablesorter")))
page=driver.page_source
except:
print("No element found")
soup=BeautifulSoup(page,'html.parser')
table=soup.select_one('.wikitable.sortable.jquery-tablesorter')  #css selector for beautiful soup
df=pd.read_html(str(table))[0]
print(df)

要将数据加载到数据框中,您需要导入以下库

import pandas as pd

如果它没有安装在您的系统中,请尝试使用进行安装

pip install pandas

最新更新