【问题标题】:selenium Web Driver does not return Wikipedia tableselenium Web Driver 不返回 Wikipedia 表
【发布时间】:2021-03-04 09:24:10
【问题描述】:

我正在尝试抓取一张表格,其中包含在美国举行的所有总统选举的结果。为此,我想使用硒。我相信我试图抓取的表是由客户端站点脚本(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")))

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

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

【问题讨论】:

  • 相同的代码,稍加添加以查看输出返回给我的原始表格。也许你在输出数据时做错了什么?
  • @Hikt,你能把修改后的代码分享给我吗?

标签: python selenium web-scraping selenium-chromedriver webdriverwait


【解决方案1】:

通过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

【讨论】:

    猜你喜欢
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    相关资源
    最近更新 更多