将字符串转换为Beautiful Soup对象

问题描述 投票:0回答:1

我对python很陌生,请在这里发布,因此,任何帮助将不胜感激!我正在尝试使用Beautiful Soup来动态解析30多个不同的RSS博客供稿。令人惊讶的是,它们不是标准的。因此,我首先创建了一个要抓取的所有潜在xml标记的列表,将其命名为标头:

headers = ['title', 'description', 'author', 'credit', 'pubDate', 'link', 'origLink']

然后,我从要抓取的RSS feed中获取所有标签,并将它们放入自己的名为标签的列表中:

import requests
from bs4 import BeautifulSoup as bs
requests.packages.urllib3.disable_warnings()

headers = ['title', 'description', 'author', 'credit', 'pubDate', 'link', 'origLink']

url = 'https://www.zdnet.com/blog/security/rss.xml'
resp = requests.get(url, verify=False)
soup = bs(resp.text, features='xml')
data = soup.find_all('item')

tags = [tag.name for tag in data[0].find_all()]
print(tags)

然后,我建立了一个新的标签列表,n_tags,两个列表中的元素重叠:

n_tags = [i for i in headers if i in tags]
print(n_tags)

然后,我遍历数据中的所有项目(页面上所有博客文章),并遍历新标签列表(与该博客相关的所有标签)中的所有元素。我被卡住的地方是n_tags是字符串列表,而不是汤对象。

解析提要的手动方式是:

for item in data:
    print(item.title.text)
    print(item.description.text)
    print(item.pubDate.text)
    print(item.credit.text)
    print(item.link.text)

但是,我想遍历标签列表并将它们插入代码中以获取xml标签的内容。

for item in data:
    for el in n_tags:
    content = item + "." + el + ".text"
    print(content)

这将返回错误:

TypeError: unsupported operand type(s) for +: 'Tag' and 'str'

我需要将列表中的字符串转换成汤“ Tag”对象,以便可以将它们连接起来。我尝试将Tag对象重铸为字符串,然后将整个字符串重新建立为汤对象,但是没有用。它没有出错,它只是返回None

content = str(item) + "." + el + ".text"
print(soup.content)

我最接近的是:

for item in data:
    for el in n_tags:
        content = str(item) + "." + el + ".text"
        print(content)

它实际上返回的是内容,但这不是我想要的,似乎没有应用“ .text”,并且对于列表中的每个元素,博客文章的内容都会重复。

我没主意,感谢您的阅读。如果您有任何问题,请告诉我。

python python-3.x beautifulsoup rss rss-reader
1个回答
0
投票

我不确定我是否正确理解您的问题,但是您似乎只是想从RSS feed中选择特定元素来选择文本。

您可以尝试使用此脚本执行此操作(使用CSS选择器):

import requests
from bs4 import BeautifulSoup as bs

url = 'https://www.zdnet.com/blog/security/rss.xml'
soup = bs(requests.get(url).content, 'html.parser')

headers = ['title', 'description', 'author', 'credit', 'pubDate', 'link', 'origLink']

for tag in soup.select(','.join(headers)):
    print(tag.text)

打印:

ZDNet | security RSS

Tue, 05 May 2020 00:15:23 +0000

ZDNet | security RSS

US financial industry regulator warns of widespread phishing campaign
FINRA warns of phishing campaign aimed at stealing members' Microsoft Office or SharePoint passwords.
Mon, 04 May 2020 23:29:00 +0000

Academics turn PC power units into speakers to leak secrets from air-gapped systems
POWER-SUPPLaY technique uses "singing capacitor" phenomenon for data exfiltration.
Mon, 04 May 2020 16:06:00 +0000

... and so on.
© www.soinside.com 2019 - 2024. All rights reserved.