我对 python 非常陌生,正在尝试构建一个脚本,最终将页面标题和 s 从指定的 URL 提取到我指定格式的 .csv 中。
我尝试使用以下命令设法让蜘蛛在 CMD 中工作:
response.xpath("/html/head/title/text()").get()
所以 xpath 一定是正确的。
不幸的是,当我运行我的蜘蛛所在的文件时,它似乎永远无法正常工作。我认为问题出在最后的代码块中,不幸的是我遵循的所有指南似乎都使用 CSS。我对 xpath 感觉更舒服,因为你可以简单地从开发工具中复制、粘贴它。
import scrapy
class PageSpider(scrapy.Spider):
name = "dorothy"
start_urls = [
"http://www.example.com",
"http://www.example.com/blog"]
def parse(self, response):
for title in response.xpath("/html/head/title/text()"):
yield {
"title": sel.xpath("Title a::text").extract_first()
}
我期望什么时候能给我上述 URL 的页面标题。
最佳答案
首先,您的第二个网址 self.start_urls
无效并返回 404,因此您最终只会提取一个标题。
其次,您需要阅读有关 selectors 的更多信息,您在 shell 测试中提取了标题,但在蜘蛛上使用它时感到困惑。
Scrapy 将调用 parse
self.start_urls
上每个 url 的方法,因此您无需迭代标题,每页只有一个。
您还可以访问<title>
直接使用 //
进行标记在 xpath 表达式的开头,请参阅从 W3Schools 复制的文本:
/ Selects from the root node
// Selects nodes in the document from the current node that match the selection no matter where they are
这是固定代码:
import scrapy
class PageSpider(scrapy.Spider):
name = "dorothy"
start_urls = [
"http://www.example.com"
]
def parse(self, response):
yield {
"title": response.xpath('//title/text()').extract_first()
}
关于python - 如何: Get a Python Scrapy to run a simple xpath retrieval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713518/