我正在尝试做一个Web爬网项目,我不断得到一个错误代码,名为“'list'object has no attribute'xpath'”/
以下是目前为止的代码:
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)
headlines = headlineNode.xpath('/a')
len(headlines)
我想把CNBC主页上的头条新闻加起来,但我总是收到一个错误的说法
^{pr2}$有什么办法解决这个问题吗?在
出现此错误的原因是xpath总是生成一个元素列表,并且可以对元素调用xpath。在
所以为了得到预期的结果,您可以在
headlineNode
列表上迭代,然后调用xpath到元素节点,比如node.xpath('/a')
下面的代码将为您提供所需的所有url的列表。你可以这样做:
这将导致:
^{pr2}$若要同时向
result_list
添加标题,可以对其进行如下修改:这将导致:
您可以参考scraping和lxml的文档以了解更多信息。在
正如您的错误所说,您试图调用列表上的
.xpath(..)
现在
^{pr2}$修复:
你需要说:
考虑将变量名重命名为
headlineNodes
以避免混淆,或者说:headlineNode = doc.xpath(..)[0]
(这可能会引发异常)。在相关问题 更多 >
编程相关推荐