【发布时间】:2017-02-07 20:56:05
【问题描述】:
对于这个项目,我正在从数据库中抓取数据并尝试将这些数据导出到电子表格中以供进一步分析。 (之前发布了here--感谢那里的帮助,我修改了我的代码!)
我之前认为在表格中查找获胜候选人可以通过始终选择表格中出现的名字来简化,因为我认为“获胜者”总是首先出现。然而,这种情况并非如此。
选举候选者是否以第一列中的图像的形式存储。我将如何抓取它并将其存储在电子表格中?
它位于
<img src="/WPAPPS/WPR/Content/Images/selected_box.gif" alt="contestant won this nomination contest">
我的问题是:我将如何使用 BeautifulSoup 解析 HTML 表并从第一列中提取一个值,该值作为图像而不是文本存储在表中。
我有一个尝试某种布尔排序度量的想法,但我不确定如何实现。
我的代码如下:
from bs4 import BeautifulSoup
import requests
import re
import csv
url = "http://www.elections.ca/WPAPPS/WPR/EN/NC?province=-1&distyear=2013&district=-1&party=-1&pageno={}&totalpages=55&totalcount=1368&secondaryaction=prev25"
rows = []
for i in range(1, 56):
print(i)
r = requests.get(url.format(i))
data = r.text
cat = BeautifulSoup(data, "html.parser")
links = []
for link in cat.find_all('a', href=re.compile('selectedid=')):
links.append("http://www.elections.ca" + link.get('href'))
for link in links:
r = requests.get(link)
data = r.text
cat = BeautifulSoup(data, "html.parser")
lspans = cat.find_all('span')
cs = cat.find_all("table")[0].find_all("td", headers="name/1")
elected = []
for c in cs:
elected.append(c.contents[0].strip())
rows.append([
lspans[2].contents[0],
lspans[3].contents[0],
lspans[5].contents[0],
re.sub("[\n\r/]", "", cat.find("legend").contents[2]).strip(),
re.sub("[\n\r/]", "", cat.find_all('div', class_="group")[2].contents[2]).strip().encode('latin-1'),
len(elected),
cs[0].contents[0].strip().encode('latin-1')
])
with open('filename.csv', 'w', newline='') as f_output:
csv_output = csv.writer(f_output)
csv_output.writerows(rows)
真的 - 任何提示将不胜感激。非常感谢。
【问题讨论】:
-
你有什么问题?
-
@Rafael 我在帖子中澄清了这个问题。我在这里转载了它:如何使用 BeautifulSoup 解析 HTML 表并从第一列中提取一个值,该值作为图像而不是文本存储在表中?
-
我们需要看表,你代码中提供的url在页面
ERROR: Search criteria is invalid. Please try selecting a new search criteria.复制了这个错误 -
代码中的url用一对大括号修改,这样可以循环遍历所有56个页面。 Here 是其中一个表的示例。第一列是相关的。
标签: python csv web-scraping beautifulsoup python-3.5