我正在尝试使用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。
最佳答案
循环遍历表行(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: [email protected]
Nome: Alessandra, Cognome: Anastasia, Email: [email protected]
...
仅供引用,
[2:]
slice 是跳过两个标题行。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))
关于python - Python BeautifulSoup抓取表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18966368/