抓取:将存储为图片的数据添加到 python 3.5 中的 CSV 文件

Scraping: add data stored as a picture to CSV file in python 3.5

对于这个项目,我正在从数据库中抓取数据并尝试将这些数据导出到电子表格以供进一步分析。 (之前发布 ——感谢您帮助修改我的代码!)

我以前认为在 table 中找到获胜候选人可以通过始终选择出现在 table 中的名字来简化,因为我认为 "winners" 总是最先出现。然而,这种情况并非如此。

是否选出了候选人,以图片的形式存储在第一列中。我如何抓取它并将其存储在电子表格中?

它位于 下:

<img src="/WPAPPS/WPR/Content/Images/selected_box.gif" alt="contestant won this nomination contest">

我的问题是:我将如何使用 BeautifulSoup 来解析 HTML table 并从存储在 table 中的第一列中提取一个值作为图像而不是文本。

我有一个尝试某种布尔排序措施的想法,但我不确定如何实施。

我的代码如下:

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)

真的--任何提示都将不胜感激。非常感谢。

This snippet 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()))

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