Skip to main content
 首页 » 编程设计

python之我可以只在特定标题之后抓取内容吗

2024年11月01日10mengfanrong

def parse_linkpage(self, response): 
    hxs = HtmlXPathSelector(response) 
    item = QualificationItem() 
    xpath = """ 
            //h2[normalize-space(.)="Entry requirements for undergraduate courses"] 
             /following-sibling::p 
            """ 
    item['Qualification'] = hxs.select(xpath).extract()[1:] 
    item['Country'] = response.meta['a_of_the_link'] 
    return item 

所以我想知道是否可以让我的代码在到达 <h2> 末尾后停止抓取.

这是网页:

<h2>Entry requirements for undergraduate courses</h2> 
<p>Example1</p> 
<p>Example2</p> 
<h2>Postgraduate Courses</h2> 
<p>Example3</p> 
<p>Example4</p> 

我想要这些结果:

Example1 
Example2 

但是我得到:

Example1 
Example2 
Example3 
Example4 

我知道我可以改变这条线,

item['Qualification'] = hxs.select(xpath).extract() 

到,

item['Qualification'] = hxs.select(xpath).extract()[0:2] 

但是这个抓取工具会查看许多不同的页面,这些页面的第一个标题中可能有超过 2 个段落,这意味着它会遗漏这些信息。

我想知道是否有一种方法可以告诉它提取我想要的 header 后面的确切数据而不是所有数据?

请您参考如下方法:

它不是很漂亮或不易阅读,但您可以使用 EXSLT 扩展到 XPath 并使用 set:difference() 操作:

>>> selector.xpath(""" 
    set:difference(//h2[normalize-space(.)="Entry requirements for undergraduate courses"] 
                    /following-sibling::p, 
                   //h2[normalize-space(.)="Entry requirements for undergraduate courses"] 
                    /following-sibling::h2[1] 
                    /following-sibling::p)""").extract() 
[u'<p>Example1</p>', u'<p>Example2</p>'] 

想法是选择目标 h2 之后的所有 p,并排除下一个 h2< 之后的那些 p/

更易读的版本:

>>> for h2 in selector.xpath('//h2[normalize-space(.)="Entry requirements for undergraduate courses"]'): 
...     paragraphs = h2.xpath("""set:difference(./following-sibling::p, 
...                                             ./following-sibling::h2[1]/following-sibling::p)""").extract() 
...     print paragraphs 
...  
[u'<p>Example1</p>', u'<p>Example2</p>'] 
>>>