【问题标题】:beautifulsoup4 - how can I print text and href at the same time?beautifulsoup4 - 如何同时打印文本和href?
【发布时间】:2018-04-08 16:42:27
【问题描述】:

我已经阅读了 10 多篇关于 print href, text 的帖子,但我找不到一篇同时打印 text 和 href 的帖子。

网站是https://cyware.com/cyber-security-news-articles

我要抓取文章的文字和网址

这是我的代码:

from urllib.request import urlopen
from bs4 import BeautifulSoup

page = urlopen("https://cyware.com/cyber-security-news-articles")
soup = BeautifulSoup(page, 'html5lib')

questions = soup.find_all('h2',{"class":"post post-v2 format-image news-card get-id"})

for h2 in soup.find_all('h2'):
    print(h2.text)
    print(h2.href)

但是href的结果是none。 我想知道为什么print(h2.href) 不打印链接。

问题包含 href="~~"

<a rel="nofollow" target="_blank" class="action_url" href="https://in.reuters.com/article/us-iran-cyber-hackers/iran-hit-by-global-cyber-attack-that-left-u-s-flag-on-screens-idINKBN1HE0MH">Iran hit by global cyber attack that left U.S. flag on screens with a warning “Don’t mess with our elections”</a>

the html source that i want parsing

result of my code

【问题讨论】:

    标签: python parsing beautifulsoup


    【解决方案1】:

    如果您想同时打印两者 - 文章的标题和相关的 href,您可以通过 html 一次性完成。获取href时,您需要搜索'a'标签。

    import requests
    import bs4 as bs
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) 
    Gecko/20100101 Firefox/20.0'}
    req = requests.get('https://cyware.com/cyber-security-news-articles', 
    headers=headers)
    
    html = bs.BeautifulSoup(req.text, "lxml")
    
    for i in html.find_all('h2',attrs={'class':"post-title post-v2-title text- 
    image"}):
        print(i.text)
        for url in i.find_all('a'):
            print(url.get('href'))
    

    【讨论】:

    • 我根据你的想法解决了这个问题,只需在 soup.find_all("a",{'rel':True},"action_url") 中使用 3 行
      : print( a.text) 打印(a.get('href'))
    • 没问题。如果这有助于您解决问题,请不要忘记接受它作为解决方案。
    【解决方案2】:

    在我看来,最好使用CSS selectors。请注意,如果您使用确切的post-title post-v2-title text-image 类定位所有h2,您的代码很容易受到网站上的更改的影响。如果维护人员将从h2 标题中重新排序或删除这些类之一,您的代码将不再工作。这是代码的精简版本,在我看来更具可读性。

    import requests
    from bs4 import BeautifulSoup
    
    req = requests.get('https://cyware.com/cyber-security-news-articles')
    
    soup = BeautifulSoup(req.text, 'lxml')
    
    for a in soup.select('.post h2[class*="title"] a'):
        print(a.text, a['href'])
    

    '.post h2[class*="title"] a' 选择属于 h2 的所有 a 的子级,其中包含 title 的类是具有 post 类的元素的子级。

    【讨论】:

      【解决方案3】:

      find_all('h2') 正在查找所有&lt;h2&gt;&lt;/h2&gt; 标头元素,这不是&lt;a href。要查找href 及其文本,请使用find_all('a')

      result = [[i.text, i['href']] for i in soup.find_all('a', {'class':'action_url'})]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-27
        • 1970-01-01
        • 2022-01-06
        • 2023-03-17
        相关资源
        最近更新 更多