繁体   English   中英

如何使用scrapy python提取在h4标签外编写的文本

[英]how to extract text written outside h4 tag using scrapy python

用蓝色标记的字段,这些是我要刮擦的字段

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

我想抓取超出h4标签的数据,即€650,000。 我如何在python中使用scrapy css做到这一点。

我正在尝试这个,但是它返回多个字段。

item['Budget'] = response.css(".txt-block h4:not(span)::text").extract()

尝试在xpath中使用following-sibling::text() 像这样: response.xpath('//div[contains(@class, "txt-block")]/h4/following-sibling::text()').get()它提供了所需的信息。

尝试使用:

data = [d.strip() for d in response.css('.txt-block::text') if d.strip()]

您想要的数据实际上在div标签中,我正在使用该标签来获取数据。

看来您正在寻找真实的演示。 查看以下实现:

import requests
from scrapy import Selector

url = "https://www.imdb.com/title/tt0111161/?pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=e31d89dd-322d-4646-8962-327b42fe94b1&pf_rd_r=702AB91P12YZ9Z98XH5T&pf_rd_s=center-1&pf_rd_t=15506&pf_rd_i=top&ref_=chttp_tt_1"

res = requests.get(url)
sel = Selector(res)
budget = ' '.join(sel.css(".txt-block:contains('Budget')::text").extract()).strip()
gross = ' '.join(sel.css(".txt-block:contains('Gross USA')::text").extract()).strip()
cumulative = ' '.join(sel.css(".txt-block:contains('Cumulative Worldwide')::text").extract()).strip()
print(f'budget: {budget}\ngross: {gross}\ncumulative: {cumulative}')

此时输出:

budget: $25,000,000
gross: $28,341,469
cumulative: $58,500,000

您需要将文本提取到数组中,并从数组中的所需位置获取值。

import scrapy
# Print Your code here
html_text="""
<div class="txt-block">'+
    <h4 class="inline">Budget:</h4>650,000
    <span class="attribute">(estimated)</span>
</div>
 """
# Parse text selector
selector=scrapy.Selector(text=html_text)
print(selector)
# Extract div
d=selector.xpath('//div[@class="txt-block"]//text()')
values=d.extract() # Gives an array of text values
print(values)
# Value index 2 is what you need
print(values[2])

Scrapy缺少BeautifulSoup中可用的标签删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM