刘硕的Scrapy笔记(三,解析构造器Selector)

2018-11-26  本文已影响0人  费云帆
from scrapy.selector import Selector


text="""
<html>
    <body>
        <h1>Hello World</h1>
        <h1>Hello Scrapy</h1>
        <b>Hello Python</b>
        <ul>
            <li>C++</li>
            <li>Java</li>
            <li>Python</li>
        </ul>
    </body>
</html>
"""
#创建Selector对象
selector=Selector(text=text)
content=selector.xpath("//h1/text()").extract()
print(content)
>>>
['Hello World', 'Hello Scrapy']
from scrapy.selector import Selector
from scrapy.http import HtmlResponse

body="""
<html>
    <body>
        <h1>Hello World</h1>
        <h1>Hello Scrapy</h1>
        <b>Hello Python</b>
        <ul>
            <li>C++</li>
            <li>Java</li>
            <li>Python</li>
        </ul>
    </body>
</html>
"""
# 创建response对象
response=HtmlResponse(url='http://www.example.com',body=body,encoding='utf-8')
# 创建Selector对象
selector=Selector(response=response)
# 选中并提取所需要的内容
content=selector.xpath('//li/text()').extract()
print(content)
>>>
['C++', 'Java', 'Python']
"""
在scrapy框架里,response对象已经有xpath()等等方法
无需再创建selector对象.
"""
selector_list=selector.xpath('//h1')
selector_list
[<Selector xpath='//h1' data='<h1>Hello World</h1>'>, <Selector xpath='//h1' data='<h1>Hello Scrapy</h1>'>]
#selector_list是一个列表,可遍历
for sel in selector_list:
    print(sel)
    
<Selector xpath='//h1' data='<h1>Hello World</h1>'>
<Selector xpath='//h1' data='<h1>Hello Scrapy</h1>'>
#提取文本
for sel in selector_list:
    print(sel.xpath('./text()'))
    
[<Selector xpath='./text()' data='Hello World'>]
[<Selector xpath='./text()' data='Hello Scrapy'>]

1.extract()
2.re()
3.extract_first()
4.re_first()

selector.xpath('//li/text()').extract()
>>>['C++', 'Java', 'Python']

写到这里,感觉有点乱,可能是累了吧,找个时间再重新整理下.

from scrapy.selector import Selector

text="""
<ul>
    <li>Python学习手册<b>价格:99.00元</b></li>
    <li>Python核心编程<b>价格:88.00元</b></li>
    <li>Python基础编程<b>价格:80.00元</b></li>
</ul>
"""
selector=Selector(text=text)
print(selector.xpath('//li/b/text()'))
#content=selector.xpath('//li/b/text()').re('\d+\.\d+')
content=selector.xpath('//li/b/text()').re_first('\d+\.\d+')
print(content)
上一篇下一篇

猜你喜欢

热点阅读