我是一个网络绘图的初学者,我有一个关于抓取多个网址的问题。在
我在我的项目中使用CNBC。我想从它的主页提取新闻标题和网址,我还想从每个网址抓取新闻文章的内容。在
到目前为止我得到的是:
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)
我一直收到一个错误,说'list'对象没有属性'content'。我想创建一个字典,其中包含每个标题的标题、每个标题的URL以及每个标题的新闻文章内容。有没有更简单的方法来解决这个问题?在
剧本开篇不错。但是,
soup = BeautifulSoup(url_node.content)
是错误的。url_content
是一个列表。您需要形成完整的新闻URL,使用请求获取HTML,然后将其传递给BeautifulSoup。在除此之外,我还想看看以下几点:
我看到了进口问题,美的不是进口的。 {cd3>添加。你在用熊猫吗?如果没有,请将其拆下。
当您查询
url_node = node.xpath('./a/@href')
时,CNN上一些带有大横幅图片的新闻div将生成一个长度为0的列表。您还需要找到适当的逻辑和选择器来获取这些新闻url。我把这事交给你。看看这个:
额外调试提示:
启动ipython3 shell并执行
%run -d yourfile.py
。查找ipdb
和调试命令。检查变量是什么以及调用的方法是否正确非常有用。在祝你好运。在
相关问题 更多 >
编程相关推荐