从网页上的 table 中提取数据
Extracting data from table on web page
我正在尝试从带有漂亮汤的网页上的 table 中提取数据。我想获取每一行单元格内的数据。
我是 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
这是生成上述错误 www.pastebin 的 html 文件。com/tQ3Cp5Wj 谢谢
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)
我正在尝试从带有漂亮汤的网页上的 table 中提取数据。我想获取每一行单元格内的数据。
我是 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
这是生成上述错误 www.pastebin 的 html 文件。com/tQ3Cp5Wj 谢谢
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)