【问题标题】:HTML parser to csv, no results in output folderHTML解析器到csv,输出文件夹中没有结果
【发布时间】:2020-01-24 01:16:39
【问题描述】:

我使用 BeautifulSoup 抓取网站以保存到 csv。当我打开 csv 时,只有标题、标题,没有数据(我抓取的链接)。

我已经尝试过“lxml”,所以我切换到了 html.parser。

from bs4 import BeautifulSoup  
import requests
import csv

page = requests.get('https://www.census.gov/programs-surveys/popest.html')
raw_html = page.text    # declare the raw_html var

soup = BeautifulSoup(raw_html, 'html.parser')  # parse the html

T = [["US Census Bureau Links"]] #Title
I = page.text

for link in soup.find_all('a', href=True):
    print(link['href'])

with open("US_Census_Bureau_links.csv","w",newline="") as f:    
    cw=csv.writer(f)                          
    cw.writerows(T)                             
    cw.writerows(I)                             

f.close()                                      

当我运行它时,我得到了 8 页的完整链接。但输出 csv 中没有链接。

【问题讨论】:

    标签: html csv parsing beautifulsoup


    【解决方案1】:

    你写入你的 csv 文件

    cw.writerows(T)
    

    但是

    T = [["US Census Bureau Links"]] #Title
    

    当你声明它时它是空的,当你写它时它保持空,因为你没有附加任何链接。因此,将您的 for 循环更改为: [根据@vladwoguer 下面的评论编辑}

    for link in soup.find_all('a', href=True):
         T.append([link['href']])
    

    它应该可以工作。

    【讨论】:

    【解决方案2】:

    您可以提取指向集合的链接,然后将其记录在文件中:

    from bs4 import BeautifulSoup  
    import requests
    import csv
    
    page = requests.get('https://www.census.gov/programs-surveys/popest.html')
    raw_html = page.text    # declare the raw_html var
    
    soup = BeautifulSoup(raw_html, 'html.parser')  # parse the html
    
    T = [["US Census Bureau Links"]] #Title
    
    links = map(lambda link: link['href'], soup.find_all('a', href=True)) # links
    
    with open("US_Census_Bureau_links.csv","w",newline="") as f:    
        cw=csv.writer(f, quoting=csv.QUOTE_ALL)                          
        cw.writerows(T)                             
        cw.writerow(links)                         
    
    f.close()                                      
    

    如果您希望每行有一个链接:

    with open("US_Census_Bureau_links.csv","w",newline="") as f:    
        cw=csv.writer(f, quoting=csv.QUOTE_ALL)                          
        cw.writerows(T)
        for link in links:                      
          cw.writerow([link])                 
    

    【讨论】:

      猜你喜欢
      • 2011-11-10
      • 2012-05-13
      • 2016-01-26
      • 2015-11-15
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多