Skip to main content
 首页 » 编程设计

python之抓取 : add data stored as a picture to CSV file in python 3. 5

2024年10月17日7artech

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

我以前认为,只需始终选择出现在表格中的名字,就可以简化在表格中查找获胜候选人的过程,因为我认为“获胜者”总是先出现。然而,这种情况并非如此。

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

它位于 下:

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

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

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

我的代码如下:

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) 

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

请您参考如下方法:

此片段将打印出民选人的名字:

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

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