python - 如何使用 BeautifulSoup 和 Python 从 <div> 标签内的 <a href> 标签获取信息?

标签 python beautifulsoup

全部。我有一个关于 BeautifulSoup with Python 的快速问题。我有几段 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&amp;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&amp;Product=8768400131 的信息);然而,我一直在试图弄清楚是否有一种方法可以在“href”属性中获取链接而无需显式搜索“class="on"”。我想我的第一个问题应该是这是否是查找此信息的最佳方式(class="on"似乎太笼统并且将来可能会中断,尽管我的 CSS 和 HTML 技能不是那么好)。我已经尝试了 find、findAll、findAllnext 等方法的多种组合,但我无法完全使其发挥作用。这主要是我所拥有的(我重新排列并更改了很多次):

productLinks = soup.find('div', attrs={'class' : 'productName'}).find('a', href=True)

如果这不是执行此操作的好方法,我怎样才能到达 <a>来自 <div class="productName"> 的标签标签?如果您需要更多信息,请告诉我。

谢谢。

最佳答案

好吧,一旦你有了 <div> , 元素, 你可以得到 <a>通过调用 find() 的子元素:

productDivs = soup.findAll('div', attrs={'class' : 'productName'})
for div in productDivs:
    print div.find('a')['href']

但是,由于 <a>紧接在<div>之上, 你可以得到 a来自 div 的属性:

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']

关于python - 如何使用 BeautifulSoup 和 Python 从 <div> 标签内的 <a href> 标签获取信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8551230/

相关文章:

python - 使用 while 循环检查小数点

python - list vs UserList 和 dict vs UserDict

python - Tkinter:斜体已经粗体的文本(重叠标签)

Python 抓取无法提取所有 <li> 的

python - 我无法使用 FIND_NEXT_SIBLING 而不是 PARENT 和 NEXT_ELEMENT 优化 beautifulsoup 查询

python - 如何使用 beautiful soup python 提取 href、alt 和 imgsrc

python - 按python中的第一组元素排序

python - 将参数从 Python 传递到 C 时出现问题

Python bs4 : How to Repeat "For" Loop with a Different Expression List if a Certain Condition is Met?

python - 在本地内容上使用 BeautifulSoup