我想检查父标签是否有一个名称不是“div”的直接子标签,所以我想检查标签的所有直接子标签。我尝试过这样的:
from bs4 import BeautifulSoup
import urllib.request
url = 'http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/#contents-children'
req = urllib.request.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36')
website = urllib.request.urlopen(req)
html = website.read()
with open("web.html", "w", encoding='utf-8') as f:
f.write(html.decode())
soup = BeautifulSoup(html, 'html.parser')
for item in soup.contents:
print(item.name)
该项目有点复杂,因此我创建了这个小测试文件。我记得去年我用这个包的时候是这样的。但是,当我使用 python3.6 BeautifulSoup4.4.0 运行此代码时,输出如下:
我尝试了所有解析器
BeautifulSoup(markup, "html.parser")
BeautifulSoup(markup, "lxml")
BeautifulSoup(markup, "xml")
BeautifulSoup(markup, "html5lib")
但他们都错了。 html.parser 甚至打印出最差的输出:( 那么我的问题是如何正确地让 children 呢?我只想要直系 child 。
---------------------10 分钟后------------------ 我尝试将此测试代码修改为:
for item in soup.body.contents:
print(item.name)
AFAIC,也许这是因为
或   被解析,但我不知道如何解决这个问题
最佳答案
你的代码没问题,但是带有 soup.contents
您正在选择 root <html>
标签和一些简单的NavigableString
对象,其名称为 None
。尝试选择汤中的一些标签,例如选择全部h3
:
for item in soup.select('h3'):
print(item.text)
将打印:
Name¶
Attributes¶
tag的名字¶
.contents 和 .children¶
.descendants¶
.string¶
.strings 和 stripped_strings¶
.parent¶
.parents¶
.next_sibling 和 .previous_sibling¶
.next_siblings 和 .previous_siblings¶
.next_element 和 .previous_element¶
.next_elements 和 .previous_elements¶
字符串¶
正则表达式¶
列表¶
True¶
方法¶
name 参数¶
keyword 参数¶
按CSS搜索¶
string 参数¶
limit 参数¶
recursive 参数¶
智能引号¶
矛盾的编码¶
需要的解析器¶
方法名的变化¶
生成器¶
XML¶
实体¶
迁移杂项¶
编辑:
检查是否<div>
标签有任何 child ,其名字不是 div
,您可以使用 lambda 函数:
for div_tag in soup.find_all('div'):
if div_tag.find(lambda t: t.name != 'div'):
print(div_tag.text)
print('-' * 80)
编辑2:
检查是否<div>
标记有任何名称不是 div
的直接子级。 ,您可以使用 lambda 函数和 CSS 选择器:
for div_tag in soup.select('div > *'):
if div_tag.find(lambda t: t.name != 'div'):
print(div_tag.text)
print('-' * 80)
关于python-3.x - 如何使用Beautifulsoup4检查父标签是否有名称不是 "div"的直接子标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51553308/