![](/img/trans.png)
[英]How Can I Get Information From An A Tag Between Two Span Tags in BeautifulSoup Using Python?
[英]How can I get information from an <a href> tag within <div> tags with BeautifulSoup and Python?
全部。 我有一个关于使用 Python 的 BeautifulSoup 的快速问题。 我有几段 HTML 看起来像这样(唯一的区别是链接和产品名称),我正在尝试从“href”属性中获取链接。
<div id="productListing1" xmlns:dew="urn:Microsoft.Search.Response.Document">
<span id="rank" style="display:none;">94.36</span>
<div class="productPhoto">
<img src="/assets/images/ocpimages/87684/00131cl.gif" height="82" width="82" />
</div>
<div class="productName">
<a class="on" href="/Products/ProductInfoDisplay.aspx?SiteId=1&Product=8768400131">CAPRI SUN - JUICE DRINK - COOLERS VARIETY PACK 6 OZ</a>
</div>
<div class="size">40 CT</div>
我目前有这个 Python 代码:
productLinks = soup.findAll('a', attrs={'class' : 'on'})
for link in productLinks:
print link['href']
这有效(对于页面上的每个链接,我都会得到类似/Products/ProductInfoDisplay.aspx?SiteId=1&Product=8768400131
); 但是,我一直在尝试弄清楚是否有办法在“href”属性中获取链接,而无需明确搜索“class =“on””。 我想我的第一个问题应该是这是否是查找此信息的最佳方式(尽管我的 CSS 和 HTML 技能不是很好,但 class="on" 似乎太笼统并且将来可能会中断)。 我已经尝试了多种 find、findAll、findAllnext 等方法的组合,但我无法让它发挥作用。 这主要是我所拥有的(我重新排列并更改了很多次):
productLinks = soup.find('div', attrs={'class' : 'productName'}).find('a', href=True)
如果这不是一个好方法,我怎样才能从<div class="productName">
标签到达<a>
标签? 如果您需要更多信息,请与我们联系。
谢谢你。
好吧,一旦有了<div>
元素,就可以通过调用find()
来获取<a>
子元素:
productDivs = soup.findAll('div', attrs={'class' : 'productName'})
for div in productDivs:
print div.find('a')['href']
但是,由于<a>
就在<div>
之上,您可以从 div 中获取a
属性:
productDivs = soup.findAll('div', attrs={'class' : 'productName'})
for div in productDivs:
print div.a['href']
现在,如果你想把所有的<a>
元素放在一个列表中,你上面的代码将不起作用,因为find()
只返回一个与其条件匹配的元素。 您将获取 div 列表并从中获取子元素,例如,使用列表推导式:
productLinks = [div.a for div in
soup.findAll('div', attrs={'class' : 'productName'})]
for link in productLinks:
print link['href']
我在 BeautifulSoup4 中给出了这个解决方案
for data in soup.find_all('div', class_='productName'):
for a in data.find_all('a'):
print(a.get('href')) #for getting link
print(a.text) #for getting text between the link
data = soup.find_all('div', class_='productName') a_class = data[0].find_all('a') url_ = a_class[0].get('href') print(url_)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.