我正在尝试获取特定标签的子标签的列表。标签是div。但是,它还有一个名为div的兄弟姐妹,它在其兄弟姐妹列表中排名第二。
enter code here
print(len(soup.body.div.main.div.section))
8
for i in range(8):
print(soup.body.div.main.div.section.contents[i].name)
None
a
div
None
script
None
input
div
print(soup.body.div.main.div.section.contents[7].name)
div
print(soup.body.div.main.div.section.div)
<div class="front-end-breadcrumb"></div>
print(len(soup.body.div.main.div.section.div))
0
print(len(soup.body.div.main.div.section.contents[2]))
0
print(len(soup.body.div.main.div.section.contents[7]))
2
print(soup.body.div.main.div.section[7])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/bs4/element.py", line 1016, in __getitem__
return self.attrs[key]
KeyError: 7
我想要的是能够获得第二个div标签的长度。通过使用...内容[7],我可以找到长度。但是,我可能并不总是知道该节的子级列表中第二个div标签在哪里。
我希望能够获得上面代码中第二个div标签的所有子标签的列表。
如果第二个div有子main,那么我希望能够调用content.div [2] .main。但是由于键盘错误,它不起作用。有什么解决方法?
这是我正在工作的网页:
https://www.indiatoday.in/magazine/cover-story/story/20071231-a-lost-cause-734888-2007-12-21
有很多html内容,所以我认为我不能发布所有内容。
答案 0 :(得分:0)
您正在使用“非标准”方式来选择元素,如果DOM树更改了,它将失败。使用find()
,findAll()
,select()
,select_one()
或阅读Docs here。
contents.div[2].main
无效,因为contents
是不是 DOM树列表。
您要选择<div class="story-section">
及其内部的所有div
吗?
# select first element
story_section = soup.find('div', class_='story-section')
# or
story_section= soup.select_one('div.story-section')
print(story_section)
# get all "div" inside ".story-section"
div_in_aricle = story_section.findAll('div')
for div in story_section:
print(div)
#To get article body
article = soup.select_one('div.description')
# or
article = soup.find('div', class_='description')
print(article.text)
# 60 REVOLUTIONS — KHALISTAN(from left) Kanwar Pal, Zaffarwal,.....