gpt4 book ai didi

python - BeautifulSoup 一无所获

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:15 26 4
gpt4 key购买 nike

这是 HTML 代码:

<div xmlns="" style="box-sizing: border-box; width: 100%; margin: 0 0 10px 0; padding: 5px 10px; background: #fdc431; font-weight: bold; font-size: 14px; line-height: 20px; color: #fff;">42263 - Unencrypted Telnet Server</div>

我正在尝试使用 Beautiful Soup 打印 42263 - Unencrypted Telnet Server 但输出是一个空元素,即 []

这是我的 Python 代码:

from bs4 import BeautifulSoup
import csv
import urllib.request as urllib2

with open(r"C:\Users\sourabhk076\Documents\CBS_1.html") as fp:
soup = BeautifulSoup(fp.read(), 'html.parser')

divs = soup.find_all('div', attrs={'background':'#fdc431'})

print(divs)

最佳答案

background 不是 div 标签的属性。 div标签的属性是:

{'xmlns': '', 'style': 'box-sizing: border-box; width: 100%; margin: 0 0 10px 0; padding: 5px 10px; background: #fdc431; font-weight: bold; font-size: 14px; line-height: 20px; color: #fff;'}

所以,要么你必须使用

soup.find_all('div', attrs={'style': 'box-sizing: border-box; width: 100%; margin: 0 0 10px 0; padding: 5px 10px; background: #fdc431; font-weight: bold; font-size: 14px; line-height: 20px; color: #fff;'}

或者,您可以使用 lambda 函数来检查 background: #fdc431 是否在 style 属性值中,如下所示:

soup = BeautifulSoup('<div xmlns="" style="box-sizing: border-box; width: 100%; margin: 0 0 10px 0; padding: 5px 10px; background: #fdc431; font-weight: bold; font-size: 14px; line-height: 20px; color: #fff;">42263 - Unencrypted Telnet Server</div>', 'html.parser')
print(soup.find(lambda t: t.name == 'div' and 'background: #fdc431' in t['style']).text)
# 42263 - Unencrypted Telnet Server

或者,您可以使用 RegEx,如 Jatimir in his answer 所示.

关于python - BeautifulSoup 一无所获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49669516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com