【问题标题】:Python BeautifulSoup scrape tablesPython BeautifulSoup 抓取表
【发布时间】:2013-09-28 18:28:05
【问题描述】:

我正在尝试使用 BeautifulSoup 创建一个表格抓取。我写了这段 Python 代码:

import urllib2
from bs4 import BeautifulSoup

url = "http://dofollow.netsons.org/table1.htm"  # change to whatever your url is

page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)

for i in soup.find_all('form'):
    print i.attrs['class']

我需要抓取 Nome、Cognome、Email。

【问题讨论】:

    标签: python html web-scraping beautifulsoup html-parsing


    【解决方案1】:

    遍历表格行(tr 标签)并获取里面的单元格文本(td 标签):

    for tr in soup.find_all('tr')[2:]:
        tds = tr.find_all('td')
        print "Nome: %s, Cognome: %s, Email: %s" % \
              (tds[0].text, tds[1].text, tds[2].text)
    

    打印:

    Nome:  Massimo, Cognome:  Allegri, Email:  Allegri.Massimo@alitalia.it
    Nome:  Alessandra, Cognome:  Anastasia, Email:  Anastasia.Alessandra@alitalia.it
    ...
    

    仅供参考,[2:] 这里的切片是跳过两个标题行。

    UPD,以下是如何将结果保存到 txt 文件:

    with open('output.txt', 'w') as f:
        for tr in soup.find_all('tr')[2:]:
            tds = tr.find_all('td')
            f.write("Nome: %s, Cognome: %s, Email: %s\n" % \
                  (tds[0].text, tds[1].text, tds[2].text))
    

    【讨论】:

    • 你能解释一下为什么在你的第一行中需要 [2:] 吗?
    • @AZhao 当然,它在答案中 - 跳过 2 个标题行。
    【解决方案2】:
    # Libray
    from bs4 import BeautifulSoup
    
    # Empty List
    tabs = []
    
    # File handling
    with open('/home/rakesh/showHW/content.html', 'r') as fp:
        html_content = fp.read()
    
        table_doc = BeautifulSoup(html_content, 'html.parser')
        # parsing html content
        for tr in table_doc.table.find_all('tr'):
            tabs.append({
                'Nome': tr.find_all('td')[0].string,
                'Cogname': tr.find_all('td')[1].string,
                'Email': tr.find_all('td')[2].string
                })
    
        print(tabs)
    

    【讨论】:

      【解决方案3】:

      OP 发布的原始链接已失效...但您可以使用gazpacho 抓取表数据:

      第 1 步 - 导入 Soup 并下载 html:

      from gazpacho import Soup
      
      url = "https://en.wikipedia.org/wiki/List_of_multiple_Olympic_gold_medalists"
      soup = Soup.get(url)
      

      第 2 步 - 查找表格和表格行:

      table = soup.find("table", {"class": "wikitable sortable"}, mode="first")
      trs = table.find("tr")[1:]
      

      第 3 步 - 使用函数解析每一行以提取所需数据:

      def parse_tr(tr):
          return {
              "name": tr.find("td")[0].text,
              "country": tr.find("td")[1].text,
              "medals": int(tr.find("td")[-1].text)
          }
      
      data = [parse_tr(tr) for tr in trs]
      sorted(data, key=lambda x: x["medals"], reverse=True)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-11
        • 2021-01-04
        • 2016-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-08
        • 2018-04-25
        • 2014-06-20
        相关资源
        最近更新 更多