【问题标题】:Getting no output while running Python Script to Scrape News Stories from CNN运行 Python 脚本从 CNN 抓取新闻故事时没有输出
【发布时间】:2017-04-19 06:00:39
【问题描述】:
import requests
from lxml import html

page = requests.get('http://www.cnn.com')
html_content = html.fromstring(page.content)

for i in html_content.iterchildren():
    print i

news_stories = html_content.xpath('//h2[@data-analytics]/a/span/text()')
news_links = html_content.xpath('//h2[@data-analytics]/a/@href')

我正在尝试运行此代码以了解 python 中的网络抓取是如何工作的。

我想从 CNN 中删除头条新闻及其链接。

当我在 Python Shell 中运行它时,我得到的 news_stories 和 news_links 的输出是:

[]

我的问题是我哪里出了问题,有没有比这个更好的方法来实现我想要的?

【问题讨论】:

    标签: python


    【解决方案1】:

    在您的代码中,html_content 仅返回页面地址,而不是页面的实际内容。

    html_content = html.fromstring(page.content)
    

    您可以尝试打印以下内容以查看该页面的完整 HTML 代码:

    import requests
    from lxml import html
    
    page = requests.get('http://www.cnn.com')
    print page.text
    

    即使您也能以某种方式获得内容,您也会从服务器获得 gzipped 响应。 (Get html using Python requests?)

    我强烈建议您使用 httplib2 库和 BeautifulSoup 从 CNN 抓取新闻报道。这真的很方便使用,让你得到你想要的。您可以在此处查看另一个 stackoverflow 帖子 (retrieve links from web page using python and BeautifulSoup)

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-05-16
      • 1970-01-01
      • 2015-11-24
      • 1970-01-01
      • 2017-06-18
      • 2020-08-16
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多