【问题标题】:python html parser not returning linkpython html解析器不返回链接
【发布时间】:2018-11-07 14:35:19
【问题描述】:

我一直在尝试解析 rss 新闻提要,但我设法获得了大多数字段,但文章的链接和发布日期除外。 这是我的代码:

import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
import re
#import xml.etree.ElementTree as ET

rss_url="https://news.google.com/news/rss/search/section/q/australia/australia?hl=en-AU&gl=AU&ned=au"
Client=urlopen(rss_url)
xml_page=Client.read()
Client.close()
soup_page=soup(xml_page,"html.parser")
#soup_page=ET.parse(xml_page)
news_list=soup_page.findAll("item")
# Print news title, url and publish date
for news in news_list:
  #text=news.text
  title=news.title.text
  link=news.link.text
  pubdate=news.pubDate.text
  description=news.description.text
  publisher = re.findall('<font color="#6f6f6f">(.*?)</font>', description)
  article_link=link
  article_info=[title,publisher,link,pubdate]
  print(article_info)

我得到了大多数字段,但 pubdate 和 link 除外。知道什么可以帮助吗?非常感谢!

【问题讨论】:

  • 发布日期和链接可以获得什么?它们是空白的吗?你有错误吗?
  • 我得到了空白返回,没有错误。

标签: python html parsing


【解决方案1】:

关于pubDatelink 字段:

pubDate 字段可以使用全小写来检索:

pubdate=news.pubdate.text

link 字段在 Beautiful Soup 的早期版本 4.5.3 中被正确捕获,但在当前版本 4.6.0 中不正确。 4.6.0 会导致您看到的空白行。使用以下内容安装 4.5.3:

$ pip3 uninstall beautifulsoup4
$ pip3 install 'beautifulsoup4==4.5.3'

这是 Beautiful Soup 的发布历史。 4.5.3 于 2017 年 1 月 2 日发布,4.6.0 于 2017 年 5 月 7 日发布。

我在 macOS 上使用 Python 3.6.0。

这里是显示所有字段的更新的前两行。

['Coalition party room split over national energy guarantee – politics live', ['The Guardian'], 'https://www.theguardian.com/australia-news/live/2018/may/29/nationals-barnaby-joyce-superannuation-coalition-banking-royal-commission-tax-politics-live', 'Mon, 28 May 2018 22:37:07 GMT']

['Residential rental agreements in Australia falling behind rest of the world: tenants union', ['ABC Online'], 'http://www.abc.net.au/news/2018-05-29/residential-rental-agreements-in-australia-need-updating/9809364', 'Mon, 28 May 2018 19:39:43 GMT']

【讨论】:

  • 感谢发布日期提示!现在可以了。但是链接仍然对我不起作用。它仍然返回空白...
  • Beautiful Soup 4.6.0 出现问题。降级到 4.5.3 工作。我已经使用pip3 命令更新了答案以卸载 4.6.0 并安装 4.5.3。
  • 我尝试使用 pip 安装 4.5.3 版本,但它一直说这是一个无效的要求...
  • 即使是 4.5.3 版的汤也无法解决链接问题。
  • 您使用的是什么版本的 Python 以及什么操作系统/版本?我在 macOS 上使用 Python 3.6.0。
猜你喜欢
  • 2016-01-18
  • 2021-10-17
  • 2017-07-11
  • 2014-08-09
  • 2014-09-09
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多