beautifulsoup4 - 如何同时打印文本和href?

时间:2018-04-08 16:42:28

标签: python parsing beautifulsoup

我已经阅读了超过10篇关于print href,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的结果是无。 我想知道为什么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

3 个答案:

答案 0 :(得分:2)

如果您想同时打印两者 - 标题和相关的文章,您可以通过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'))

答案 1 :(得分:1)

在我看来,使用plunker会更好。请注意,如果您使用完全post-title post-v2-title text-image类定位所有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'

a选择所有h2的{​​{1}}子项,其中包含title的类,该类是具有post类的元素的子元素。

答案 2 :(得分:0)

find_all('h2')正在查找所有<h2></h2>标头元素,而不是<a href。要查找href及其文字,请使用find_all('a')

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