我是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()
}我希望当它给我的网页标题的上述网址。
发布于 2019-04-17 02:01:51
首先,你在self.start_urls上的第二个url是无效的,返回404,所以你最终只提取了一个标题。
其次,您需要阅读更多关于selectors的信息,您在shell上提取了测试标题,但在您的爬行器上使用它时感到困惑。
Scrapy会为self.start_urls上的每个url调用parse方法,所以你不需要遍历标题,每个页面只有一个。
您还可以在xpath表达式的开头使用//直接访问<title>标记,请参见从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()
}https://stackoverflow.com/questions/55713518
复制相似问题