Python Scrapy 并不总是从网站下载数据

标签 python request response scrapy sites

Scrapy 用于解析 html 页面。我的问题是为什么有时scrapy会返回我想要的响应,但有时却不返回响应。是我的错吗?这是我的解析函数:

class AmazonSpider(BaseSpider):
    name = "amazon"
    allowed_domains = ["amazon.org"]
    start_urls = [
       "http://www.amazon.com/s?rh=n%3A283155%2Cp_n_feature_browse-bin%3A2656020011"
   ]

def parse(self, response):
            sel = Selector(response)
            sites = sel.xpath('//div[contains(@class, "result")]')
            items = []
            titles = {'titles': sites[0].xpath('//a[@class="title"]/text()').extract()}
            for title in titles['titles']:
                item = AmazonScrapyItem()
                item['title'] = title
                items.append(item)
            return items

最佳答案

我相信您只是没有使用最合适的 XPath 表达式。

Amazon 的 HTML 有点乱,不是很统一,因此不太容易解析。但经过一些试验后,我可以使用以下 parse 函数提取几个搜索结果的所有 12 个标题:

def parse(self, response):
    sel = Selector(response)
    p = sel.xpath('//div[@class="data"]/h3/a')
    titles = p.xpath('span/text()').extract() + p.xpath('text()').extract()
    items = []
    for title in titles:
        item = AmazonScrapyItem()
        item['title'] = title
        items.append(item)
    return items

如果您关心结果的实际顺序,上述代码可能不合适,但我相信情况并非如此。

关于Python Scrapy 并不总是从网站下载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20289450/

相关文章:

列表性能中的Python模糊匹配字符串

python - Scrapy脚本运行无异常,但没有收集到数据

php - Symfony2 响应

python - 哪个R包提供了类似于pythons urllib的功能

python - 如何访问和可视化预训练的 TensorFlow 2 模型中的权重?

python - 不规则间距堆积点的计算方法

apache - 使用 Mod_JK 在 JBoss 服务器上测量请求处理时间

javascript - Nodejs 从嵌套函数返回结果

javascript - 无法使用 Testcafe 拦截来自页面的传出 AJAX 请求

java - "request"和 "response"变量或值是在 Java EE 中预定义的吗?