【问题标题】:Example on webcrawling news headlines and contents in Python使用 Python 抓取新闻标题和内容的示例
【发布时间】:2017-04-12 02:27:02
【问题描述】:

我是 WebCrawling 的初学者,我有一个关于爬取多个 url 的问题。

我在我的项目中使用 CNBC。我想从它的主页中提取新闻标题和url,我还想从每个url中抓取新闻文章的内容。

这是我目前得到的:

import requests
from lxml import html 
import pandas

url = "http://www.cnbc.com/"
response = requests.get(url) 
doc = html.fromstring(response.text)

headlineNode = doc.xpath('//div[@class="headline"]')
len(headlineNode)

result_list  = []
for node in headlineNode : 
    url_node = node.xpath('./a/@href')
    title = node.xpath('./a/text()')
    soup = BeautifulSoup(url_node.content)
    text =[''.join(s.findAll(text=True)) for s in soup.findAll("div", {"class":"group"})]
    if (url_node and title and text) : 
        result_list.append({'URL' : url + url_node[0].strip(),
                            'TITLE' : title[0].strip(),
                            'TEXT' : text[0].strip()})
print(result_list)
len(result_list)

我不断收到错误消息,说“列表”对象没有属性“内容”。我想创建一个字典,其中包含每个标题的标题、每个标题的 url 以及每个标题的新闻文章内容。有没有更简单的方法来解决这个问题?

【问题讨论】:

  • 但是你的 url 是一个包含 cnbc 网址的字符串,所以它没有 .content 属性也就不足为奇了。也许你的意思是 url_code.content?
  • @Bemmu 仍然不起作用,但我已经编辑了问题!
  • 你确定没有保护内容的js吗

标签: python xpath beautifulsoup web-crawler


【解决方案1】:

脚本的良好开端。但是,soup = BeautifulSoup(url_node.content) 是错误的。 url_content 是一个列表。您需要形成完整的新闻 URL,使用请求获取 HTML,然后将其传递给 BeautifulSoup。

除此之外,还有几件事我会看:

  1. 我看到导入问题,BeautifulSoup 未导入。 将from bs4 import BeautifulSoup 添加到顶部。你在用熊猫吗?如果没有,请将其删除。

  2. 当您查询url_node = node.xpath('./a/@href') 时,CNN 上一些带有大横幅图片的新闻 div 将产生一个长度为 0 的列表。您还需要找到适当的逻辑和选择器来获取这些新闻 URL。我将把它留给你。

看看这个:

import requests
from lxml import html
import pandas
from bs4 import BeautifulSoup

# Note trailing backslash removed
url = "http://www.cnbc.com"
response = requests.get(url)
doc = html.fromstring(response.text)

headlineNode = doc.xpath('//div[@class="headline"]')
print(len(headlineNode))

result_list  = []
for node in headlineNode:
    url_node = node.xpath('./a/@href')
    title = node.xpath('./a/text()')
    # Figure out logic to get that pic banner news URL
    if len(url_node) == 0:
        continue
    else:
        news_html = requests.get(url + url_node[0])
        soup = BeautifulSoup(news_html.content)
        text =[''.join(s.findAll(text=True)) for s in soup.findAll("div", {"class":"group"})]
        if (url_node and title and text) :
            result_list.append({'URL' : url + url_node[0].strip(),
                                'TITLE' : title[0].strip(),
                                'TEXT' : text[0].strip()})
print(result_list)
len(result_list)

额外调试提示:

启动 ipython3 shell 并执行%run -d yourfile.py。查找ipdb 和调试命令。检查您的变量是什么以及您是否调用了正确的方法非常有帮助。

祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    相关资源
    最近更新 更多