【发布时间】:2020-07-31 10:50:27
【问题描述】:
我需要一些帮助来抓取这样的一系列页面:https://electionresults.ewashtenaw.org/electionreporting/aug2018/precinctreport1.html。 URL 很容易筛选——要进入下一页,您只需提高“区域报告”后的数字即可。我特别想只获得第二个“州长”部分的投票总数,包括 Abdul El-Sayed、Shri Thanedar 和 Gretchen Whitmer。问题是,我使用第一个区域页面(我刚刚链接的那个页面)使用 selenium 制作了我的脚本,并且 xpath 因页面而异。所以当我运行我的脚本时,它停在第二页,因为它找不到元素。我怎么能解决这个问题? 这是我的代码:
import pandas as pd
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
#
# Finds the total number of precincts to be scraped
driver = webdriver.Chrome(executable_path="/users/aliallam/Desktop/scraper test/chromedriver")
url = 'https://electionresults.ewashtenaw.org/electionreporting/aug2018/indexprecinctreport.html'
driver.get(url)
precinct_nums = driver.find_elements_by_class_name('regular')
driver.close()
# Perm vars
precincts = []
all_abdul_votes = []
all_shri_votes = []
all_gretchen_votes = []
def ScrapePrecinct(precinct):
# Initial Selenium stuff
driver = webdriver.Chrome(executable_path="/users/aliallam/Desktop/scraper test/chromedriver")
url = f'https://electionresults.ewashtenaw.org/electionreporting/aug2018/precinctreport{precinct}.html'
driver.get(url)
# Find Precinct Name
precinct_text = driver.find_element_by_class_name('h2').text
# Find vote numbers for each candidate & assign to variable
abdul_votes = driver.find_element_by_xpath('/html/body/center/table/tbody/tr[73]/td[4]').text
shri_votes = driver.find_element_by_xpath('/html/body/center/table/tbody/tr[75]/td[4]').text
gretchen_votes = driver.find_element_by_xpath('/html/body/center/table/tbody/tr[77]/td[4]').text
# Append all data from precinct to perm vars
precincts.append(precinct_text)
all_abdul_votes.append(abdul_votes)
all_shri_votes.append(shri_votes)
all_gretchen_votes.append(gretchen_votes)
driver.quit()
itterations = len(precinct_nums)
counter = "1"
while int(counter) <= itterations:
ScrapePrecinct(counter)
counter = str(int(counter) + 1)
print(precincts)
print(all_abdul_votes)
print(all_shri_votes)
print(all_gretchen_votes)
【问题讨论】:
-
请提供一份所需输出的样本,以方便我们使用
标签: python selenium selenium-webdriver beautifulsoup