【发布时间】:2023-03-18 06:49:02
【问题描述】:
所以我一直试图从this页面的大桌子上刮取所有赢得美国总统大选的总统的选举人票。
这是我一直在尝试使用的代码:
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(r'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.CSS_SELECTOR,".wikitable.sortable.jquery-tablesorter")))
finally:
page = driver.page_source
soup = BeautifulSoup(page, 'lxml')
table = soup.find('table', {'class': 'wikitable sortable
jquerytablesorter'})
#print(table)
rows=table.find_all('tr')
到目前为止,代码的工作原理。这是应该获取我需要的信息的代码部分。
for row in rows:
need=row.find_all('td')
for n in need:
try:
if len(n.find('b')==0):
continue
else:
if nek.find('b').find('sup'):
continue
electoral_votes=n.find('span',{'style':"position: relative margin: 0
0.3em;"}).get_text()
print(electoral_votes)
except:continue
运行这部分代码后,代码没有返回任何我需要的东西。
有人可以帮帮我吗?
我会很高兴的
【问题讨论】:
-
你能修正你的缩进吗?见stackoverflow.com/help/formatting
-
你要什么表?这里不需要使用 selenium。
-
@chitown88 是的,我在编写代码后就知道了。为了回答您的问题,我在页面上最大的表格之后。看不懂我可以附上截图。
-
@JustinEzequiel 很抱歉缩进不佳,我对在这个网站上提问有点陌生,所以对我来说还是有点奇怪。谢谢。
标签: python html web-scraping beautifulsoup tags