gpt4 book ai didi

python - BeautifulSoup:如何跳过 find_all 中的子节点?

转载 作者:太空宇宙 更新时间:2023-11-04 03:25:14 25 4
gpt4 key购买 nike

我有以下代码来抓取此页面:

soup = BeautifulSoup(html)
result = u''
# Find Starting point
start = soup.find('div', class_='main-content-column')
if start:
news.image_url_list = []
for item in start.find_all('p'):

我面临的问题是它也捕获了 <p>里面<div class="type-gallery"> ,我想避免。但是找不到实现它的方法。有什么想法吗?

enter image description here

最佳答案

您想要直接子代,而不仅仅是任何后代,这就是element.find_all() 返回的内容。你最好的选择是使用 CSS selector相反:

for item in soup.select('div.main-content-column > div > p'):

> 运算符将此限制为 p 标记,这些标记是 divdiv 标记的直接子节点> 与给定的类(class)。您可以根据需要将其具体化;添加 itemprop 属性,例如:

for item in soup.select('div.main-content-column > div[itemprop="articleBody"] > p'):

另一种方法是遍历 element.children iterable :

start = soup.find('div', class_='main-content-column')
if start:
news.image_url_list = []
for item in start.children:
if item.name != 'div':
# skip children that are not <div> tags
continue
for para in item.children:
if item.name != 'p':
# skip children that are not <p> tags
continue

关于python - BeautifulSoup:如何跳过 find_all 中的子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33331231/

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