Python BeautifulSoup scrape tables
Я пытаюсь создать таблицу scrape с помощью 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, электронную почту.
Ответы
Ответ 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: [email protected]
Nome: Alessandra, Cognome: Anastasia, Email: [email protected]
...
FYI, [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))
Ответ 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)