【问题标题】:Identify same elements if they don't have different classes如果它们没有不同的类,则识别相同的元素
【发布时间】:2018-06-28 05:24:23
【问题描述】:

我试图抓取页面 http://apps.leg.wa.gov/wac/default.aspx?cite=296-17A&full=true 以获得类型的输出

'6903-03' : u'Aerial spraying, seeding, crop dusting, or firefighting' ,
'6510-00' : u'Domestic servants/home care assistants employed in or about the private residence
of a home owner' ,
'1407-00' : u'Bus companies' ,

我正在使用scrapy。我使用了以下 xpath

response.xpath('//*[@id="ctl00_ContentPlaceHolder1_dlSectionContent"]/span/div/span/text()').extract())

即使它可以正常工作,但它也会返回一些不需要的行,就像这些

u'which also provide farm kill operations away from the custom meat shop',
u'Farm kill operations',
u'only',
u'no farm kill',
u'only',
u'4302-16 Farm kill',
u'exclusively',
u'only; ',
u'only',
u'no farm kill',
u'including farm kill',

我试图想到的一种方法是在每一行上做一个正则表达式,以将正则表达式的模式行标识为u'(?:\d{2}){2}-(?:\d{1}){2} [A-Za-z ]*'

有没有更好或更简洁的方法来识别此类跨度。

PS:- 跨度没有任何类。他们只有风格。我不确定是否可以使用样式来识别所需的跨度。

【问题讨论】:

  • 即。 xpath("//span[@style="font-weight:bold;text-indent:0in;"]/text()") - 但页面可能需要更复杂的 xpath。
  • 您应该添加 2-3 个不同元素的 html 示例。

标签: python xpath scrapy


【解决方案1】:

XPath 可能更具体,并包含 h3 标记以便能够引用其下一个兄弟

'//*[@id="ctl00_ContentPlaceHolder1_dlSectionContent"]/descendant::h3/following-sibling::div[1]/span/text()'

可以在 Linux/Cygwin 中测试

xmllint --recover --html --xpath '//*[@id="ctl00_ContentPlaceHolder1_dlSectionContent"]/descendant::h3/following-sibling::div[1]/span' ~/tmp/test.html| sed -re 's%<span style=[^>]+>([^<]+)</span>%\1\n%g' | less

样本输出

0101-00 Land clearing: Highway, street and road construction, N.O.C.
0103-09 Drilling or blasting: N.O.C.
0104-12 Dredging, N.O.C.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-08
    • 2020-04-29
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多