【问题标题】:Can't retreive href with BeautifulSoup无法使用 BeautifulSoup 检索 href
【发布时间】:2018-03-28 13:28:49
【问题描述】:

我正在尝试使用 BeautifulSoup 在 for 循环中检索 href。 我用一些find_all 整理了HTML 中不相关的部分。我最近做的是:

events = soup.find_all("a", attrs={"class": "event-link-wrap"})

然后我像这样运行一个 for 循环:

for event in events:
    href = event.find("href")
    category = event.find("p",{"class": "category"})
    title = event.find("h3")
    arena = event.find("span", {"class": "venue"})

当我打印 href 时,我得到 None。会不会是 href 在我使用 find_all 的类中?如果我打印 event 我得到:

<a class="event-link-wrap" href="https://www.WHATIWANT.COM/HERE title="More Info">
<div class="thumb">
<img alt="pic_125x125.jpg" src="https://www.test.com/pic.jpg"/> </div>
<div class="info clearfix">
<p class="category">CATEGORY HERE</p>
<h3>EVENT TITLE HERE</h3>
<p class="date"><span class="m-date__rangeFirst"><span class="m-date__day"> 6 </span></span><span class="m-date__separator"> - </span><span class="m-date__rangeLast"><span class="m-date__day"> 7 </span><span class="m-date__month">april</span></span> <span class="venue"> ARENA HERE</span> </p>
</div>
<div class="buttons">
<span class="icon"></span>
<span class="icon-hover"></span>
</div>
</a>

我想要的 href 在第一个标签中。除了href之外,我可以检索我想要的所有内容。我如何获得href?就像我提到的,现在它返回的只是None

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    您可以通过__getitem__ 访问href

    events = [i['href'] for i in soup.find_all("a", attrs={"class": "event-link-wrap"})]
    

    【讨论】:

      【解决方案2】:

      由于您正在循环遍历 &lt;a&gt; 标记,该标记本身包含您所追求的 href,因此您可以使用 href = event['href'] 直接获取 href

      find() 方法需要一个标签作为它的第一个参数,而不是一个属性。因此,在代码中的任何位置使用find('href') 将始终返回None

      只需使用这个:

      for event in events:
          href = event["href"]
          ...
      

      【讨论】:

        【解决方案3】:

        尝试:

        events = soup.find_all("a", class_="event-link-wrap")
        for event in events:
            href = event.get("href")
        

        【讨论】:

          猜你喜欢
          • 2015-02-27
          • 2016-01-14
          • 2021-12-26
          • 1970-01-01
          • 1970-01-01
          • 2017-09-01
          • 2016-09-22
          • 2017-11-10
          • 2019-09-29
          相关资源
          最近更新 更多