【问题标题】:How to fetch a href link under p using BeautifulSoup如何使用 BeautifulSoup 获取 p 下的 href 链接
【发布时间】:2020-09-15 11:38:20
【问题描述】:

我正在尝试从父网页获取指向另一篇文章的指针链接。下面的代码显示了网站的外观。所有指针网页均以http://lenta.ru/开头。

所以我的代码试图从源 html 代码中找到那个 href 元素。

但是它不会打印文章底部的指针链接。

import requests
from lxml import html
from bs4 import BeautifulSoup
from urllib.request import urlopen

tmp = "https://uynaa.wordpress.com/2011/05/04/%d0%be%d1%81%d0%b0%d0%bc%d0%b0-%d0%b1%d0%b8%d0%bd-%d0%bb%d0%b0%d0%b4%d0%b5%d0%bd%d0%b8%d0%b9%d0%b3-%d1%8f%d0%b0%d0%b6-%d0%b8%d0%bb%d1%80%d2%af%d2%af%d0%bb%d1%81%d1%8d%d0%bd-%d0%b1%d1%8d/"
html = urlopen(tmp).read()
soup = BeautifulSoup(html, "lxml")

for a in soup.find_all('a', href=True):
    if "lenta.ru" in a:
        print(a)

我该怎么做?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您的变量a 不是字符串;它的类型为bs4.element.Tag。如果要在href属性中查找文字,可以这样写:

    for a in soup.find_all('a', href=True):
        if "lenta.ru" in a.get('href', ''):
            print(a)
    

    对于您提供的链接,这将返回:

    <a href="http://lenta.ru/articles/2011/05/02/lamort/">http://lenta.ru/articles/2011/05/02/lamort/</a>
    <a href="http://lenta.ru/articles/2011/05/02/lamort/" rel="nofollow" target="_blank">lenta.ru/articles/2011/05…</a>
    <a href="http://lenta.ru/articles/2013/10/03/mourning/" rel="nofollow" target="_blank">lenta.ru/articles/2013/10…</a>
    <a href="http://lenta.ru/articles/2013/09/30/freezone/" rel="nofollow" target="_blank">lenta.ru/articles/2013/09…</a>
    <a href="http://lenta.ru/articles/2012/08/21/terranova/" rel="nofollow" target="_blank">lenta.ru/articles/2012/08…</a>
    

    如果您想进一步限制您的结果,您可以将搜索限制在 div 类的 entry 元素:

    for a in soup.select('div.entry a'):
        if "lenta.ru" in a.get('href', ''):
            print(a)
    

    这将输出:

    <a href="http://lenta.ru/articles/2011/05/02/lamort/">http://lenta.ru/articles/2011/05/02/lamort/</a>
    

    【讨论】:

      猜你喜欢
      • 2021-01-01
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      相关资源
      最近更新 更多