我正在尝试从网页上的表格中提取数据,并提供美味的汤。我想在每行的单元格中获取数据。
我是python的新手已尝试过以下代码片段,但它不起作用:
import urllib.request
fname = r"C:\Python34\page.htm"
HtmlFile = open(fname, 'r', encoding='utf-8')
source_code = HtmlFile.read()
from bs4 import BeautifulSoup
soup = BeautifulSoup(source_code, 'html.parser')
table = soup.find( "table", {"title":"geoip-demo-results-tbody"} )
rows=list()
for row in table.findAll("tr"):
rows.append(row)
for tr in rows:
cols = tr.findAll('td')
p = col[0].string.strip()
d = col[1].string.strip()
print(p)
print(d)
编辑:我收到此错误
回溯(最近一次调用最后一次):文件“C:\ Python34 \ scrip.py”,第14行,在d = cols [1] .text.strip()中
IndexError:列出索引超出范围的行“
84.78.229.78ESSantander,
Cantabria,
Cantabria,
Sp ain,
Europe3900143.4647,
-3.8044Orange EspanaOrange Espana
这是生成上述错误的html文件www.pastebin.com/tQ3Cp5Wj谢谢
答案 0 :(得分:1)
fname = r"F:\Vikas\jobs\temp\page.htm"
HtmlFile = open(fname, 'r', encoding='utf-8')
source_code = HtmlFile.read()
from bs4 import BeautifulSoup
soup = BeautifulSoup(source_code, 'html.parser')
table = soup.find('tbody', id='geoip-demo-results-tbody')
rows = table.find_all('tr')
for tr in rows:
cols = tr.find_all('td')
p = cols[0].text.strip()
d = cols[1].text.strip()
print(p)
print(d)