【问题标题】:Can't grab next sibling using css selector within scrapy无法在scrapy中使用css选择器抓取下一个兄弟
【发布时间】:2020-11-26 00:33:48
【问题描述】:

我正在尝试使用在其中实现 css 选择器的 scrapy 来获取预算。我可以在使用 xpath 时得到它,但如果是 css 选择器,我会迷路。我什至可以在使用 BeautifulSoup 并使用 next_sibling 时获取内容。

我试过了:

import requests
from scrapy import Selector

url = "https://www.imdb.com/title/tt0111161/"

res = requests.get(url)
sel = Selector(res)
# budget = sel.xpath("//h4[contains(.,'Budget:')]/following::text()").get()
# print(budget)

budget = sel.css("h4:contains('Budget:')::text").get()
print(budget)

我使用 css 选择器得到的输出:

Budget:

预期输出:

$25,000,000

html的相关部分:

<div class="txt-block">
            <h4 class="inline">Budget:</h4>$25,000,000
            <span class="attribute">(estimated)</span>
        </div>

website address

该站点中的该部分显示为:

在scrapy中使用css选择器如何获取预算信息?

【问题讨论】:

  • css 选择器不考虑 HTML 之外的标签,xpath 考虑。

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


【解决方案1】:

此选择器.css("h4:contains('Budget:')::text") 正在选择h4 标记,而您想要的文本在它的父元素div 中。

你可以使用.css('div.txt-block::text'),但这会返回几个元素,因为页面有几个这样的元素。 CSS 选择器没有父伪元素,我想你可以使用.css('div.txt-block:nth-child(12)::text'),但如果你要抓取更多页面,这可能会在其他页面中失败。

最好的选择是使用 XPath:

response.xpath('//h4[text() = "Budget:"]/parent::div/text()').getall()

【讨论】:

  • 我已经在上述脚本中使用了一个 xpath,它可以完美地抓取该内容。我可以创建一个 css 选择器sel.css(".txt-block:has(&gt; h4:contains('Budget:'))::text").get(),它会和你的一样,但不幸的是,scrapy 支持非常有限的伪 css 选择器,这就是它会失败的原因。
  • 作为建议,您实际上需要//h4[etc]/following-sibling::text()[1],因为要求div 也将包含(estimated) 文本(我刚刚注意到原始问题做得正确,虽然被注释掉了)
猜你喜欢
  • 2011-12-13
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
  • 2013-08-31
  • 2019-04-26
  • 2012-04-17
  • 1970-01-01
  • 2016-04-02
相关资源
最近更新 更多