python - 我无法使用 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”
解决方案
如果您得到响应代码而不是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
推荐阅读
- java - 为什么 volatile 静态变量不刷新?
- typescript - 类型中缺少属性但在不同类型中需要?
- python - 如何将 RGBA 颜色传递给 Seaborn PairGrid
- postgresql - 使用 s3_uri 将 s3 csv 导入 PostgreSQL
- ios - SwiftUI 键盘弹出一次输入并不断出现和消失
- python - ValueError: Input 0 is in compatible with layer vggface_resnet50: expected shape=(None, 224, 224, 3), found shape=(None, 1, 224, 224, 3)
- ip - 无法使用 keepalived 和 VRRP 设置浮动 IP
- r - R Shiny 链接多个输入以控制 1 个输出
- javascript - 选择下拉菜单中的最后一个选项或计算 ui vision rpa kantu selenium katalon 记录器的下拉菜单中的选项数
- python - Python:打印的对象有类型但返回的对象是NoneType?