【问题标题】:Scraping: add data stored as a picture to CSV file in python 3.5抓取:将存储为图片的数据添加到 python 3.5 中的 CSV 文件
【发布时间】: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


【解决方案1】:

This sn-p will print the name of the elected person:

from bs4 import BeautifulSoup
import requests
req  = requests.get("http://www.elections.ca/WPAPPS/WPR/EN/NC/Details?province=-1&distyear=2013&district=-1&party=-1&selectedid=8548")
page_source = BeautifulSoup(req.text, "html.parser")
table = page_source.find("table",{"id":"gvContestants/1"})
for row in table.find_all("tr"):
    if not row.find("img"):
        continue
    if "selected_box.gif" in row.find("img").get("src"):
        print(''.join(row.find("td",{"headers":"name/1"}).text.split()))

作为旁注,请不要用无意义的名称声明变量。它会伤害任何试图帮助您的人的眼睛,并且将来再次查看代码时会伤害您

【讨论】:

    猜你喜欢
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2020-06-16
    • 1970-01-01
    • 2018-04-16
    • 2020-10-11
    相关资源
    最近更新 更多