目录
1.如何伪装请求?
2.如何选择解析网页的库?
常见的库:
- re:追求解析效率的选择
优点:解析速度极快
缺点:编写耗时较多,不易理解和维护,没有相应支持 - bs4(beautifulsoup):入门选择
优点:功能丰富(支持XPath语法、CSS选择器等),容易理解
缺点:编写繁琐,解析速度较慢,开销大 - lxml:进阶选择
优点:编写耗时少,解析速度快,支持XPath语法
缺点:不易理解 - requests-html:支持丰富的选择
优点:代码量少,灵活方便,功能齐全(支持JS动态加载、XPath语法、CSS选择器等)
缺点:无明显缺点,只是依赖库较多 - selectolax:新的选择
优点:解析速度极快,支持CSS选择器
缺点:无明显缺点
# 官方示例
In [1]: from selectolax.parser import HTMLParser
...:
...: html = """
...: <h1 id="title" data-updated="20201101">Hi there</h1>
...: <div class="post">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </div>
...: <div class="post">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
...: """
...: tree = HTMLParser(html)
In [2]: tree.css_first('h1#title').text()
Out[2]: 'Hi there'
In [3]: tree.css_first('h1#title').attributes
Out[3]: {
'id': 'title', 'data-updated': '20201101'}
In [4]: [node.text(