【发布时间】: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