2019独角兽企业重金招聘Python工程师标准>>>
###1. 安装
pip install requests或者easy_install requests
###2. 基本使用
在ipython中利用自动补全看下调用requests之后返回的response对象的一些属性:
In [1]: import requests
In [2]: r = requests.get('https://api.github.com')
In [3]: r.
r.apparent_encoding r.history r.raw
r.close r.is_redirect r.reason
r.connection r.iter_content r.request
r.content r.iter_lines r.status_code
r.COOKIEs r.json r.text
r.elapsed r.links r.url
r.encoding r.ok
r.headers r.raise_for_status
快速入门:http://requests-docs-cn.readthedocs.io/zh_CN/latest/user/quickstart.html
高级的用法:http://requests-docs-cn.readthedocs.io/zh_CN/latest/user/advanced.html
lxml安装方法(很多同学在安装过程中遇到了问题),见我的上一篇博客。
使用requests库获取到网页内容后,再通过lxml解析,也可通过BeautifulSoup等等工具
lxml是基于C语言库libxml2和libxslt的python化绑定,其对XML(HTMl)有强大的处理能力,并且向下兼容Python的ElementTree API,支持Xpath和BeautifulSoup解析, 使用起来非常方便。
官方教程:http://lxml.de/
下面是一个在Windows平台下用python3.5用lxml解析HTML的例子,lxml通过xpath表达式来获取数据
(详见:http://www.cnblogs.com/descusr/archive/2012/06/20/2557075.html):
World News only on this page ... and this is a parsed fragment ...from lxml import etreehtml = '''
Top News
'''page = etree.HTML(html.lower())
hrefs = page.xpath(u"//a")
for href in hrefs:# print(href.attrib)print(href.text)