28

我正在尝试用 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。

4

3 回答 3

50

遍历表格行(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))
于 2013-09-23T18:40:00.633 回答
0

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)
于 2020-10-10T02:36:37.933 回答
0
# 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)
于 2019-10-04T11:58:38.833 回答