gpt4 book ai didi

python - 使用 BeautifulSoup 以特定属性定位

转载 作者:行者123 更新时间:2023-11-28 21:49:09 24 4
gpt4 key购买 nike

我正在尝试抓取具有如下部分的页面:

<a name="id_631"></a>

<hr>

<div class="store-class">
<div>
<span><strong>Store City</strong</span>
</div>

<div class="store-class-content">
<p>Event listing</p>
<p>Event listing2</p>
<p>Event listing3</p>
</div>

<div>
Stuff about contact info
</div>
</div>

页面是这样的部分的列表,区分它们的唯一方法是通过 <a> 中的名称属性。标签。

所以我想我想定位到 next_sibling 以获取 <hr>然后再次交给下一个 sibling 以获得<div class="store-class">部分。我只需要该 div 标签中的信息。

我不确定如何定位 <a>标签向下移动两个 sibling 。当我尝试 print(soup.find_all('a', {"name":"id_631"}))那只是给我标签中的内容,什么都没有。

这是我的脚本:

import requests
from bs4 import BeautifulSoup

r = requests.get("http://www.tandyleather.com/en/leathercraft-classes")

soup = soup = BeautifulSoup(r.text, 'html.parser')

print(soup.find("a", id="id_631").find_next_sibling("div", class_="store-class"))

但是我得到了错误:

Traceback (most recent call last):
File "tandy.py", line 8, in <module>
print(soup.find("a", id="id_631").find_next_sibling("div", class_="store-class"))
AttributeError: 'NoneType' object has no attribute 'find_next_sibling'

最佳答案

find_next_sibling()救援:

soup.find("a", attrs={"name": "id_631"}).find_next_sibling("div", class_="store-class")

此外,html.parser 必须替换为 lxmlhtml5lib

另见:

关于python - 使用 BeautifulSoup 以特定属性定位 <a>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33926946/

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