【发布时间】:2020-10-02 10:10:35
【问题描述】:
我正在解析这个 RSS 提要:
https://www.google.com/alerts/feeds/12700550304290381537/6239785894655863043
我正在使用以下代码:
import requests
from bs4 import BeautifulSoup
url = "https://www.google.com/alerts/feeds/12700550304290381537/6239785894655863043"
resp = requests.get(url)
soup = BeautifulSoup(resp.content, features='xml')
items = soup.findAll('entry')
news_items = []
for item in items:
news_item = {}
news_item['title'] = item.title.text
news_item['link'] = item.link['href']
news_item['published'] = item.published.text
news_item['source'] = item.link
news_items.append(news_item)
news_items[0]
我得到以下输出:
{'link': <link href="https://www.google.com/url?rct=j&sa=t&url=https://duitslandinstituut.nl/artikel/38250/duitsland-lanceert-corona-tracing-app&ct=ga&cd=CAIyGWFlODkwMWNhMWM0YmE4ODU6bmw6bmw6Tkw&usg=AFQjCNHDFPconO3h8mpzJh92x4HrjPL2tQ"/>,
'published': '2020-06-11T15:33:11Z',
'source': <link href="https://www.google.com/url?rct=j&sa=t&url=https://duitslandinstituut.nl/artikel/38250/duitsland-lanceert-corona-tracing-app&ct=ga&cd=CAIyGWFlODkwMWNhMWM0YmE4ODU6bmw6bmw6Tkw&usg=AFQjCNHDFPconO3h8mpzJh92x4HrjPL2tQ"/>,
'title': 'Duitsland lanceert <b>corona</b>-tracing-<b>app</b>'}
但是,我正在寻找的输出是:
{'link': 'https://duitslandinstituut.nl/artikel/38250/duitsland-lanceert-corona-tracing-app&ct=ga&cd=CAIyGWFlODkwMWNhMWM0YmE4ODU6bmw6bmw6Tkw&usg=AFQjCNHDFPconO3h8mpzJh92x4HrjPL2tQ',
'published': '2020-06-11T15:33:11Z',
'source': 'Duitslandinstituut'
'title': 'Duitsland lanceert corona-tracing-app'}
所以,首先,我想丢失谷歌链接部分。其次,我希望来源是第二个“https://”之后的名称,大写字母。第三,我想从标题中删除任何 等属性。我打算将结果放入参考书目,因此文本不能包含任何计算机代码。
我尝试在 BS4 中解决此问题,但无法解决。有人建议我之后使用正则表达式在 pandas df 中执行此操作,但我不熟悉正则表达式,并且很难理解示例。有人有解决办法吗?
【问题讨论】:
标签: python beautifulsoup xml-parsing rss