【问题标题】:How can I get an element inside a class with scrapy using response.css如何使用 response.css 在一个带有scrapy的类中获取一个元素
【发布时间】:2018-09-30 07:26:18
【问题描述】:

我正在尝试从以下位置获取 value="3474636382675":

<input class="lst" value="3474636382675" title="Zoeken" autocomplete="off" id="sbhost" maxlength="2048" name="q" type="text">

我试过了

response.css(".lst >value").extract()

这个可行,但我正在恢复一切,我只需要价值。

response.css(".lst").extract()

【问题讨论】:

    标签: python-3.x web-scraping scrapy


    【解决方案1】:

    使用 CSS,您可以像这样选择所需的属性:

    response.css(".lst::attr(value)").extract()
    

    您可以在 Scrapy 的 documentation 中详细了解选择器

    【讨论】:

    • 就是这样。非常感谢
    【解决方案2】:

    不太确定css。但是 here is one 来自另一个 SO 答案。或者尝试 xpath:

    response.xpath('//input[@class="lst"]/@value').extract()
    

    或者如果你只需要一个值:

    response.xpath('//input[@class="lst"]/@value').extract_first()
    

    【讨论】:

    • 它适用于 xpath,谢谢。但是你会如何使用 response.css 呢?
    • 在我看来是合法的。
    • @Rousblack 似乎其他人已经回答了您的问题。您也可以点击链接,看看答案是否适合您。
    【解决方案3】:

    我使用漂亮的汤来解析 html。这是一个从 yahoo Finance 获取股票价格的示例。

    import urllib.request
    from bs4 import BeautifulSoup
    
    def getPrice(tag):
        source = "https://finance.yahoo.com/quote/"+tag
        filehandle = urllib.request.urlopen(source)
        soup = BeautifulSoup(filehandle.read(), "html.parser")
        priceSpan = soup.findAll("span", { "class" : "Fz(36px)" })
        for k in priceSpan:
            return(k.getText())
    
    def getDayChange(tag):
        source = "https://finance.yahoo.com/quote/"+tag
        filehandle = urllib.request.urlopen(source)
        soup = BeautifulSoup(filehandle.read(), "html.parser")
        priceSpan = soup.findAll("span", { "class" : "Fw(500)" })
        for k in priceSpan:
            return(k.getText())
    

    https://gist.github.com/Krewn/0e624d35c396df63262dd42d74f2beb6

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-07
      • 2021-12-12
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      相关资源
      最近更新 更多