繁体   English   中英

如何使用 BeautifulSoup 从网页中抓取结构化表格?

[英]How do i scrape a structured table from a webpage using BeautifulSoup?

我有以下代码来抓取网站( https://www.vesselfinder.com/vessels/STENAWECO-ENERGY-IMO-9683984-MMSI-538005270 )。 由于存在相似的类名,因此很难确定表类名以将数据抓取到 CSV 文件。 我如何确保我正在抓取正确的信息?

我的代码是

agent = {"User-Agent":'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'} 
urlFile = requests.get('https://www.vesselfinder.com/vessels/STENAWECO-ENERGY-IMO-9683984-MMSI-538005270', headers = agent)

soupHtml = BeautifulSoup(urlFile.content, 'lxml')

rowsFind = soupHtml.find_all("table",{"class": "tparams"})
print(rowsFind)
for i in rowsFind:
    z = i.find_all("tr")
for r in z:
    cols = r.find_all('td' , 'v3')
    cols = [x.text.strip() for x in cols]
    print(cols)
    AISVessel.append(cols[0])

AIStable.append(AISVessel)    

现在我有这个错误:

IndexError: list index out of range

所需的输出将是:

[['Tanker' , 'Marshall Islands' , 'USHOU > DOSPM' , 'Jan 3, 19:00' , '9683984 / 538005270' , '  V7CJ5', '183 / 32 m' ,  '11.4 m' ,' 115.4° / 13.5 kn ' , '19.60436 N/80.84751 W' , 'Jan 1, 2020 07:38 UTC']]

我想将上面反映的相关数据附加到嵌套列表中,以支持将其写入 CSV 文件。

要找到正确的表格,您可以使用 CSS 选择器h2:contains("AIS Data") ~ table.tparams td.v3 - 这将获得表格中所有带有标题“AIS Data”的<td>

import requests
from bs4 import BeautifulSoup

agent = {"User-Agent":'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
urlFile = requests.get('https://www.vesselfinder.com/vessels/STENAWECO-ENERGY-IMO-9683984-MMSI-538005270', headers = agent)

soupHtml = BeautifulSoup(urlFile.content, 'lxml')

out = [td.get_text(strip=True) for td in soupHtml.select('h2:contains("AIS Data") ~ table.tparams td.v3')]

print(out)

印刷:

['Tanker', 'Marshall Islands', 'USHOU > DOSPM', 'Jan 3, 19:00', '9683984 / 538005270', 'V7CJ5', '183 / 32 m', '11.4 m', '115.4° / 13.5 kn', '19.60436 N/80.84751 W', 'Jan 1, 2020 07:38 UTC']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM