1. response.xpath()。get(default = None)
getメソッドにはデフォルトパラメータNoneがあります。抽出されない場合はデフォルトでNoneを返し、それ以外の場合はデフォルト値を返します。ソースコード:
def get(self, default=None):
"""
Return the result of ``.get()`` for the first element in this list.
If the list is empty, return the default value.
"""
for x in self:
return x.get()
else:
return default
例:
response.xpath( '// div [@ id = "not-exists"] / text()')。get(default = 'not-found')
'見つかりません'
2.response.xpath()。re()またはresponse.xpath()。re_first()
セレクターオブジェクトは、正規表現を使用してリストまたはstrを返すこともできます。
response.xpath( '// a [contains(@href、 "image")] / text()')。re(r'Name:\ s *(。*) ') [' My image 1 '、 ' My画像2 '、 'マイ画像3 '、 'マイ画像4 '、 'マイ画像5 ']
response.xpath( '// a [contains(@href、 "image")] / text()')。re_first(r'Name:\ s *(。*) ') ' My image 1 '
3.xpath()文法はcount()を使用してカウントします
例:特定のulタグの下に9つのliサブタグがあるulタグxpath構文を検索します// ul [count(li)= 9]
response.xpath( '// div [count(a)= $ cnt] / @ id'、cnt = 5).get() '画像'
4.スクレイピーフレームワークでは、lxmlを介してxpathを解析する必要はありません
>>> from scrapy import Selector
>>> doc = u"""
... <div>
... <ul>
... <li class="item-0"><a href="link1.html">first item</a></li>
... <li class="item-1"><a href="link2.html">second item</a></li>
... <li class="item-inactive"><a href="link3.html">third item</a></li>
... <li class="item-1"><a href="link4.html">fourth item</a></li>
... <li class="item-0"><a href="link5.html">fifth item</a></li>
... </ul>
... </div>
... """
>>> sel = Selector(text=doc, type="html")
>>> sel.xpath('//li//@href').getall()
['link1.html', 'link2.html', 'link3.html', 'link4.html', 'link5.html']
>>> sel.xpath('//li[re:test(@class, "item-\d$")]//@href').getall()
['link1.html', 'link2.html', 'link4.html', 'link5.html']
正規表現
test()
たとえば、この 関数は、XPath が十分でない場合、starts-with()
または contains()
十分でない場合に非常に役立ち ます。
5.xpathその他の使用法
from scrapy import Selector
str1 = """
<p class="foo bar-baz">First</p>
<p class="foo">Second</p>
<p class="bar">Third</p>
<p>Fourth</p>
"""
s = Selector(text=str1, type='html')
# ret1,ret2结果等价
ret1 = s.xpath('//p[has-class("foo")]').getall() # 有class属性且值为foo的p标签
ret2 = s.xpath('//p[contains(@class,"foo")]').getall() # class属性包含foo的p标签
ret3 = s.xpath('//p[has-class("foo", "bar-baz")]').getall() # foo 且 bar-baz
print(ret1, ret2, ret3)