Python BeautifulSoup刮表

kin*_*ope 17 html python beautifulsoup html-parsing web-scraping

我正在尝试用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']
Run Code Online (Sandbox Code Playgroud)

我需要刮Nome,Cognome,Email.

ale*_*cxe 32

循环表行(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)
Run Code Online (Sandbox Code Playgroud)

打印:

Nome:  Massimo, Cognome:  Allegri, Email:  Allegri.Massimo@alitalia.it
Nome:  Alessandra, Cognome:  Anastasia, Email:  Anastasia.Alessandra@alitalia.it
...
Run Code Online (Sandbox Code Playgroud)

仅供参考,[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))
Run Code Online (Sandbox Code Playgroud)