【问题标题】:Having trouble being specific enough to scrape what I want from a tag with Beautiful Soup and Python无法具体到使用 Beautiful Soup 和 Python 从标签中抓取我想要的内容
【发布时间】:2017-08-14 19:55:43
【问题描述】:

这是我要抓取的 html 示例。

<a id="catalogEntry_img3677183" href="http://www.academy.com/shop/pdp/under-armour%E2%84%A2-mens-tide-chaser-short-sleeve-shirt#repChildCatid=4099002" title="Under Armour Men's Tide Chaser Short Sleeve Shirt" onclick="javascript:dlTrackProductGridClicks(&quot;109457178&quot;,&quot;Under Armour Men's Tide Chaser Short Sleeve Shirt&quot;,&quot;3677183&quot;);">

我想检索 href 属性的引号内的链接。这是我写的代码。

    a_ids = page_soup.findAll("a")

    for a in range(len(a_ids)):
        output = a_ids[a]["href"]
        print(output)

但是,我从这段代码中得到的结果包括一堆来自其他 a 标签的乱七八糟的东西,如下所示。

<a href="http://www.academy.com/shop/pdp/bcg-mens-turbo-mesh-short-sleeve-t-
shirt#repChildCatid=4190420" id="catalogEntry_img4181006" 
onclick="javascript:dlTrackProductGridClicks(&quot;109409336&quot;,&quot;BCG 
Men's Turbo Mesh Short Sleeve T-shirt&quot;,&quot;4181006&quot;);" 
title="BCG Men's Turbo Mesh Short Sleeve T-shirt">
<img alt="BCG Men's Turbo Mesh Short Sleeve T-shirt" onerror="this.onerror=null;this.src='//content.academy.com/weblib/images/coming-
soon.jpg';" src="//assets.academy.com/mgen/12/10740412.jpg?is=500,500"/>
<div class="product-info-attributes">
<!-- BEGIN AYRPriceDisplay.jspf -->
<div class="z-pricing" id="offerPrice_4181006">
        $9.99           
    </div>

我只想要 href 标记中的链接。如何定位我想要的特定链接?作为参考,我试图抓取的网址来自这里:http://www.academy.com/shop/browse/apparel/mens-apparel/mens-shirts--t-shirts

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    不需要 len 函数,因为 find_all 返回一个列表。

    做事

    a_ids = soup.find_all("a") 
    for a in a_ids:
        output = a["href"]
        print(output)
    

    甚至更短:

    hrefs = [a['href'] for a in soup.find_all('a')]
    for a in hrefs:
        print(a)
    

    【讨论】:

      【解决方案2】:

      试试这个:

      from bs4 import BeautifulSoup, SoupStrainer
      
      
      page_soup = """<a id="catalogEntry_img3677183" href="http://www.academy.com/shop/pdp/under-armour%E2%84%A2-mens-tide-chaser-short-sleeve-shirt#repChildCatid=4099002" title="Under Armour Men's Tide Chaser Short Sleeve Shirt" onclick="javascript:dlTrackProductGridClicks(&quot;109457178&quot;,&quot;Under Armour Men's Tide Chaser Short Sleeve Shirt&quot;,&quot;3677183&quot;);">"""
      
      
      soup = BeautifulSoup(page_soup,'html.parser')
      
      
      a_ids = soup.findAll("a")
      
      for a in range(len(a_ids)):
          output = a_ids[a]["href"]
          print(output)
      

      我认为指定解析器类型会有所不同

      【讨论】:

      • 你说得对。我得到了我需要的东西,谢谢 pyjg。
      猜你喜欢
      • 1970-01-01
      • 2021-12-04
      • 2020-04-22
      • 2015-04-07
      • 1970-01-01
      • 2020-04-28
      • 2015-07-19
      • 2017-05-27
      • 2020-10-11
      相关资源
      最近更新 更多