首页 > 解决方案 > 我无法使用 BeautifulSoup 从表中提取数据

问题描述

我正在尝试使用beautifulsoup 刮两张桌子并撞到一堵砖墙。网站:https ://bgp.he.net/country/US我正在尝试从表格中获取标题行,但由于某种原因无法将其解析为列表,因此我可以对其进行操作。然后我想从每一列中获取数据并将其全部输出到 JSON 文件中。

例子:

for row in soup.find_all("tr"):

   #Append to list(?)

删除不需要的条目?

我希望能够将其输出到 JSON 文件并像这样显示。

ASN #:国家:“US”,“名称”:XXX,“Routes V4”,“XXXX”,“Routes V6”,“XXX”

标签: pythonweb-scrapingbeautifulsoupformatting

解决方案


如果您得到响应代码而不是200在标头中设置 User-Agent,我的 get 403 Forbidden.

headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0'}
html = requests.get('https://bgp.........', headers=headers)

soup = BeautifulSoup(html.text, 'html.parser')
#print(soup)
data = []
for row in soup.find_all("tr")[1:]: # start from second row
    cells = row.find_all('td')
    data.append({
        'ASN': cells[0].text,
        'Country': 'US',
        "Name": cells[1].text,
        "Routes V4": cells[3].text,
        "Routes V6": cells[5].text
    })

print(data)

结果:

[
  {'ASN': 'AS6939', 'Country': 'US', 'Name': 'Hurricane Electric LLC', 'Routes V4': '127,337', 'Routes V6': '28,227'},
  {'ASN': 'AS174', 'Country': 'US', 'Name': 'Cogent Communications', 'Routes V4': '118,159', 'Routes V6': '8,814'}
]

获取国家和代码

country = soup.select_one('h2 img').get('title')
# United State
country_code = 'https://bgp.he.net/country/US'.split('/')[-1]
# US

推荐阅读