【问题标题】:Difference between HtmlResponse requests.responseHtmlResponse requests.response 之间的区别
【发布时间】:2020-11-07 16:24:13
【问题描述】:

我想提取this website webpage的香水品牌的所有链接。

我想做一个能找到所有href的scrapy scraper,就像我对BeautifulSoup所做的那样:

    soup = BeautifulSoup(requests.get('https://www.nosetime.com'+ url, 
                                      headers=headers).content, 'html.parser')
    print(soup)
    result = soup.find_all('a', {'class': 'imgborder'})
    for r in result:
        brand_url = r.attrs['href']

requests.get returns a Response object这里

但是这种自制技术会因 403 错误而崩溃,所以我想制作一个 scrapy 刮板,因为本教程声称它可以处理这些错误。

import scrapy
from bs4 import BeautifulSoup

class NosetimeScraper(scrapy.Spider):
    name = "nosetime"
    urls = ['/pinpai/2-a.html']
    start_urls = ['https://www.nosetime.com' + url for url in urls]

    def parse(self, response):
        # proceed to other pages of the listings
        soup = BeautifulSoup(response.content, 'html.parser')
        results = soup.find_all('a', {'class': 'imgborder'})
        for r in results:
            brand_url = r.attrs['href']
            yield scrapy.Request(url=brand_url, callback=self.parse)

        # then do something with the scrapy.Request() response that has been yielded ...

但它会返回:

soup = BeautifulSoup(response.content, 'html.parser')
AttributeError: 'HtmlResponse' object has no attribute 'content'

所以我猜 HtmlResponse requests.response 之间有区别?

【问题讨论】:

    标签: python-3.x python-requests request response


    【解决方案1】:

    这是因为scrapy.http.HtmlResponserequests.models.Response 不同。您可以改用response.body

    但是将.css() 与 Scrapy 一起使用会更好:

    def parse(self, response):
        urls = response.css('a.imgborder::attr(href)').getall()
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)
    

    【讨论】:

    • 谢谢,你有关于如何通过 CSS 抓取的教程或资源吗?我更习惯用 beautifulsoup 这样做
    • 查看 Mozilla 的 MDN 文档:developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors。您始终可以通过按 F12 在 devtools 中测试您的选择器。这对于大多数网站来说已经足够了,但是如果您需要更大的灵活性,也可以考虑学习 xpath,它被称为 .xpath()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2020-05-10
    • 2014-09-20
    • 2010-10-28
    • 2015-10-04
    • 2012-08-12
    • 2011-02-18
    相关资源
    最近更新 更多