python - 如何: Get a Python Scrapy to run a simple xpath retrieval

标签 python scrapy

我对 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/

相关文章:

python - 类型错误 : 'Request' object is not subscriptable

python - 如何在scrapy中挖掘链接中的站点

python - 导入错误 : No module named flask. ext.security.datastore.SQLAlchemyUserDatastore

python - 如何将 DataFrame 列的非空条目合并到一个新列中?

Robot框架中的Python - Se2Lib没有属性 'execute'

scrapy - 覆盖 Scrapy 输出格式 'on the fly'

python - 如何用Scrapy爬取整个网站?

python - 无法使用scrapy从网页中获取不同列表的标题

python - 像 list(str(my_integer)) 那样进行两种类型的转换是 pythonic 吗?

python - 使用 selenium webdriver 在 Windows 上设置 firefox 二进制文件的路径