测试 beautifulsoup 中是否存在子标签
Test if children tag exists in beautifulsoup
我有一个 XML 文件,其结构已定义但标签数量不同,例如
file1.xml:
<document>
<subDoc>
<id>1</id>
<myId>1</myId>
</subDoc>
</document>
file2.xml:
<document>
<subDoc>
<id>2</id>
</subDoc>
</document>
现在我想检查标签 myId
是否存在。所以我做了以下事情:
data = open("file1.xml",'r').read()
xml = BeautifulSoup(data)
hasAttrBs = xml.document.subdoc.has_attr('myID')
hasAttrPy = hasattr(xml.document.subdoc,'myID')
hasType = type(xml.document.subdoc.myid)
结果是
file1.xml:
hasAttrBs -> False
hasAttrPy -> True
hasType -> <class 'bs4.element.Tag'>
file2.xml:
hasAttrBs -> False
hasAttrPy -> True
hasType -> <type 'NoneType'>
好的,<myId>
不是 <subdoc>
的属性。
但是如果存在子标签,我该如何测试?
//编辑:顺便说一句:我真的不喜欢遍历整个子文档,因为那样会很慢。我希望找到一种方法可以直接 address/ask 该元素。
你可以这样处理:
for child in xml.document.subdoc.children:
if 'myId' == child.name:
return True
查找子标签是否存在的最简单方法就是
childTag = xml.find('childTag')
if childTag:
# do stuff
更具体地针对 OP 的问题:
如果不了解XML文档的结构,可以使用汤的.find()
方法。像这样:
with open("file1.xml",'r') as data, open("file2.xml",'r') as data2:
xml = BeautifulSoup(data.read())
xml2 = BeautifulSoup(data2.read())
hasAttrBs = xml.find("myId")
hasAttrBs2 = xml2.find("myId")
如果您确实知道该结构,则可以像这样 xml.document.subdoc.myid
通过访问作为属性的标签名称来获取所需的元素。所以整个事情会像这样:
with open("file1.xml",'r') as data, open("file2.xml",'r') as data2:
xml = BeautifulSoup(data.read())
xml2 = BeautifulSoup(data2.read())
hasAttrBs = xml.document.subdoc.myid
hasAttrBs2 = xml2.document.subdoc.myid
print hasAttrBs
print hasAttrBs2
版画
<myid>1</myid>
None
if tag.find('child_tag_name'):
这是一个检查 Instagram 中是否存在 h2 标签的示例 URL。希望你觉得它有用:
import datetime
import urllib
import requests
from bs4 import BeautifulSoup
instagram_url = 'https://www.instagram.com/p/BHijrYFgX2v/?taken-by=findingmero'
html_source = requests.get(instagram_url).text
soup = BeautifulSoup(html_source, "lxml")
if not soup.find('h2'):
print("didn't find h2")
你可以用 if tag.myID:
如果要检查 myID
是否是 child 的直接 child 而不是 child 的 child 使用 if tag.find("myID", recursive=False):
如果要检查标签是否没有 child,请使用 if tag.find(True):
page = requests.get("http://dataquestio.github.io/web-scraping-pages/simple.html")
page
soup = BeautifulSoup(page.content, 'html.parser')
testNode = list(soup.children)[1]
def hasChild(node):
print(type(node))
try:
node.children
return True
except:
return False
if( hasChild(testNode) ):
firstChild=list(testNode.children)[0]
if( hasChild(firstChild) ):
print('I found Grand Child ')
如果您使用的是 CSS 选择器
content = soup_elm.select('.css_selector')
if len(content) == 0:
return None
你也可以这样试试:
response = requests.get("Your URL here")
soup = BeautifulSoup(response.text,'lxml')
RESULT = soup.select_one('CSS_SELECTOR_HERE') # for one element search
print(RESULT)
请注意,Bs4 的 CSS 选择器与其他选择器方法略有不同。
Click Here for documentation on how to use CSS selectors.
soup.select
适用于所有元素选择,也适用于具有属性的元素。
我有一个 XML 文件,其结构已定义但标签数量不同,例如
file1.xml:
<document>
<subDoc>
<id>1</id>
<myId>1</myId>
</subDoc>
</document>
file2.xml:
<document>
<subDoc>
<id>2</id>
</subDoc>
</document>
现在我想检查标签 myId
是否存在。所以我做了以下事情:
data = open("file1.xml",'r').read()
xml = BeautifulSoup(data)
hasAttrBs = xml.document.subdoc.has_attr('myID')
hasAttrPy = hasattr(xml.document.subdoc,'myID')
hasType = type(xml.document.subdoc.myid)
结果是 file1.xml:
hasAttrBs -> False
hasAttrPy -> True
hasType -> <class 'bs4.element.Tag'>
file2.xml:
hasAttrBs -> False
hasAttrPy -> True
hasType -> <type 'NoneType'>
好的,<myId>
不是 <subdoc>
的属性。
但是如果存在子标签,我该如何测试?
//编辑:顺便说一句:我真的不喜欢遍历整个子文档,因为那样会很慢。我希望找到一种方法可以直接 address/ask 该元素。
你可以这样处理:
for child in xml.document.subdoc.children:
if 'myId' == child.name:
return True
查找子标签是否存在的最简单方法就是
childTag = xml.find('childTag')
if childTag:
# do stuff
更具体地针对 OP 的问题:
如果不了解XML文档的结构,可以使用汤的.find()
方法。像这样:
with open("file1.xml",'r') as data, open("file2.xml",'r') as data2:
xml = BeautifulSoup(data.read())
xml2 = BeautifulSoup(data2.read())
hasAttrBs = xml.find("myId")
hasAttrBs2 = xml2.find("myId")
如果您确实知道该结构,则可以像这样 xml.document.subdoc.myid
通过访问作为属性的标签名称来获取所需的元素。所以整个事情会像这样:
with open("file1.xml",'r') as data, open("file2.xml",'r') as data2:
xml = BeautifulSoup(data.read())
xml2 = BeautifulSoup(data2.read())
hasAttrBs = xml.document.subdoc.myid
hasAttrBs2 = xml2.document.subdoc.myid
print hasAttrBs
print hasAttrBs2
版画
<myid>1</myid>
None
if tag.find('child_tag_name'):
这是一个检查 Instagram 中是否存在 h2 标签的示例 URL。希望你觉得它有用:
import datetime
import urllib
import requests
from bs4 import BeautifulSoup
instagram_url = 'https://www.instagram.com/p/BHijrYFgX2v/?taken-by=findingmero'
html_source = requests.get(instagram_url).text
soup = BeautifulSoup(html_source, "lxml")
if not soup.find('h2'):
print("didn't find h2")
你可以用 if tag.myID:
如果要检查 myID
是否是 child 的直接 child 而不是 child 的 child 使用 if tag.find("myID", recursive=False):
如果要检查标签是否没有 child,请使用 if tag.find(True):
page = requests.get("http://dataquestio.github.io/web-scraping-pages/simple.html")
page
soup = BeautifulSoup(page.content, 'html.parser')
testNode = list(soup.children)[1]
def hasChild(node):
print(type(node))
try:
node.children
return True
except:
return False
if( hasChild(testNode) ):
firstChild=list(testNode.children)[0]
if( hasChild(firstChild) ):
print('I found Grand Child ')
如果您使用的是 CSS 选择器
content = soup_elm.select('.css_selector')
if len(content) == 0:
return None
你也可以这样试试:
response = requests.get("Your URL here")
soup = BeautifulSoup(response.text,'lxml')
RESULT = soup.select_one('CSS_SELECTOR_HERE') # for one element search
print(RESULT)
请注意,Bs4 的 CSS 选择器与其他选择器方法略有不同。 Click Here for documentation on how to use CSS selectors.
soup.select
适用于所有元素选择,也适用于具有属性的元素。