【发布时间】: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