gpt4 book ai didi

python - 使用 Beautifulsoup 和 Mechanize 从元素中解析 href 属性值

转载 作者:太空宇宙 更新时间:2023-11-03 13:46:11 24 4
gpt4 key购买 nike

谁能帮我遍历一棵带有漂亮汤的html树?

我正在尝试通过 html 输出进行解析,并在收集每个值后插入到名为 Tld 的表中使用 python/django

<div class="rc" data-hveid="53">
<h3 class="r">
<a href="https://billing.anapp.com/" onmousedown="return rwt(this,'','','','2','AFQjCNGqpb38ftdxRdYvKwOsUv5EOJAlpQ','m3fly0i1VLOK9NJkV55hAQ','0CDYQFjAB','','',event)">Billing: Portal Home</a>
</h3>

并且只解析href的值<a> 的属性,所以只有这一部分:

https://billing.anapp.com/

属于:

<a href="https://billing.anapp.com/" onmousedown="return rwt(this,'','','','2','AFQjCNGqpb38ftdxRdYvKwOsUv5EOJAlpQ','m3fly0i1VLOK9NJkV55hAQ','0CDYQFjAB','','',event)">Billing: Portal Home</a>

我目前有:

for url in urls:
mb.open(url)
beautifulSoupObj = BeautifulSoup(mb.response().read())
beautifulSoupObj.find_all('h3',attrs={'class': 'r'})

问题是find_all以上,距离 <a> 还不够远元素。

非常感谢任何帮助。谢谢。

最佳答案

from bs4 import BeautifulSoup

html = """
<div class="rc" data-hveid="53">
<h3 class="r">
<a href="https://billing.anapp.com/" onmousedown="return rwt(this,'','','','2','AFQjCNGqpb38ftdxRdYvKwOsUv5EOJAlpQ','m3fly0i1VLOK9NJkV55hAQ','0CDYQFjAB','','',event)">Billing: Portal Home</a>
</h3>
"""

bs = BeautifulSoup(html)
elms = bs.select("h3.r a")
for i in elms:
print(i.attrs["href"])

打印:

https://billing.anapp.com/

h3.r acss selector

您可以使用 css 选择器(我更喜欢它们)、xpath 或在元素中查找。选择器 h3.r a 将查找所有具有类 rh3 并从其中获取 a 元素。它可能是一个更复杂的例子,比如 #an_id table tr.the_tr_class td.the_td_class 它会在给定的 td 中找到一个 id,它属于给定类的 tr,当然在一个表中。

这也会给你相同的结果。 find_all 返回一个 bs4.element.Tag 的列表,find_all 有一个递归字段不确定你是否可以在一行中完成,我个人更喜欢 css 选择器,因为它简单干净。

for elm in  bs.find_all('h3',attrs={'class': 'r'}):
for a_elm in elm.find_all("a"):
print(a_elm.attrs["href"])

关于python - 使用 Beautifulsoup 和 Mechanize 从元素中解析 href 属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19983165/

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