Python 在单个字符串中获取每个段落文本时,正确的xpath/css是什么?
首先,我创建一个HtmlResponse并使用scrapy读取它:Python 在单个字符串中获取每个段落文本时,正确的xpath/css是什么?,python,xpath,scrapy,Python,Xpath,Scrapy,首先,我创建一个HtmlResponse并使用scrapy读取它: from scrapy.http import HtmlResponse from scrapy.selector import Selector body = """ <div class="a"> <p> text1<br> text2 </p> </div> <div class="a"> <p>
from scrapy.http import HtmlResponse
from scrapy.selector import Selector
body = """
<div class="a">
<p>
text1<br> text2
</p>
</div>
<div class="a">
<p>
text3
</p>
</div>
"""
response = HtmlResponse(url='http://example.com/', body=body)
sel = Selector(response)
正如你所注意到的,我得到了2个段落的3个文本元素?如何仅获取2个文本元素
[u'text1 text2',u'text3']
请注意,我不喜欢使用
BeautifulSoup
,因为性能是这里的一项要求。我使用了这个使用压缩的解决方案,也许其他人可以有更好的选择:
[''.join(x.xpath('./text()').extract()) for x in sel.xpath('//div[@class="a"]/p')]
## [u'\n text1 aa\n ', u'\n text3\n ']
使用CSS选择器(包括Scrapy的::text
扩展名):
>>从scrapy.http导入HtmlResponse
>>>从scrapy.selector导入选择器
>>>
>>>body=”“”
...
…
…text1
text2
...
...
…
…文本3
...
... """
>>>response=HtmlResponse(url=)http://example.com/,body=body)
>>>sel=选择器(响应)
>>>[u'。为sel.css('div.a>p')中的段落连接(段落.css('::text').extract()).strip()]
[u'text1 text2',u'text3']
>>>
谢谢+1相当于我的,但使用css。我检查它是否使用清洁剂(清洁剂溶液)。
[''.join(x.xpath('./text()').extract()) for x in sel.xpath('//div[@class="a"]/p')]
## [u'\n text1 aa\n ', u'\n text3\n ']
>>> from scrapy.http import HtmlResponse
>>> from scrapy.selector import Selector
>>>
>>> body = """
... <div class="a">
... <p>
... text1<br> text2
... </p>
... </div>
... <div class="a">
... <p>
... text3
... </p>
... </div>
... """
>>> response = HtmlResponse(url='http://example.com/', body=body)
>>> sel = Selector(response)
>>> [u''.join(paragraph.css('::text').extract()).strip() for paragraph in sel.css('div.a > p')]
[u'text1 text2', u'text3']
>>>