Python 使用beautifulSoup在没有类的情况下从标记中进行刮取

Python 使用beautifulSoup在没有类的情况下从标记中进行刮取,python,web-scraping,beautifulsoup,Python,Web Scraping,Beautifulsoup,如果我想从锚点标记中的href属性和字符串水平零位置刮取链接 因为锚定标记没有自己的类,在整个源代码中有更多的锚定标记 使用beautifulSoup可以做些什么来获取所需的数据 <div class="prodName"> <a href="/product.php?sku=123;name=Horizon Zero Dawn">Horizon Zero Dawn</a></div> 锚标记没有自己的类并不重要。通过查找父div,然后查找具有

如果我想从锚点标记中的href属性和字符串水平零位置刮取链接

因为锚定标记没有自己的类,在整个源代码中有更多的锚定标记

使用beautifulSoup可以做些什么来获取所需的数据

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

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

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()
编辑:

评论后更新。如果页面中有多个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)

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

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()
编辑:

评论后更新。如果页面中有多个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)