gpt4 book ai didi

python - 使用 beautifulSoup 从没有类的标签中抓取

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:48 29 4
gpt4 key购买 nike

如果我想从 anchor 标记中的 href 属性和字符串“水平零黎明”中抓取链接。

由于 anchor 标记没有自己的类,并且整个源代码中还有更多的 anchor 标记。

我可以使用 beautifulSoup 来抓取我需要的数据做什么?

<div class="prodName">
<a href="/product.php?sku=123;name=Horizon Zero Dawn">Horizon Zero Dawn</a></div>

最佳答案

anchor 标记没有自己的类并不重要。通过找到父 div,然后找到具有适当 href 属性和文本的 anchor ,我们可以提取所需的两个值:

from bs4 import BeautifulSoup

page = '<div class="prodName"><a href="/product.php?sku=123;name=Horizon Zero Dawn">Horizon Zero Dawn</a></div>'

soup = BeautifulSoup(page)

div = soup.find('div', {'class': 'prodName'})
a = div.find('a', {'href': True}, text='Horizon Zero Dawn')

print a['href']
print a.get_text()

这打印:

/product.php?sku=123;name=Horizon Zero Dawn
Horizon Zero Dawn

编辑:

评论后更新。如果页面中有多个 div 元素,则需要遍历它们并找到每个元素中存在的所有 a 元素,如下所示:

import requests
from bs4 import BeautifulSoup

url ='https://in.webuy.com/product.php?scid=1'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text,'html.parser')
for div in soup.findAll('div',{'class':'prodName'}):
a = div.findAll('a')
for link in a:
href = link.get('href')
print(href)

关于python - 使用 beautifulSoup 从没有类的标签中抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44200994/

29 4 0