Python爬虫_基础

来源:互联网 发布:联合国条约数据库 编辑:程序博客网 时间:2024/06/05 05:50

Python版本3.0+

注:学习用散记,仅做入门和回忆用。

1.关于urllib

先看一个返回状态码的例子,在Ajax中用XHR对象的status属性获取,在这里:

#!/user/bin/python#coding=utf-8import urllib.requestresponse=urllib.request.urlopen('http://www.baidu.com')print(response.getcode())

返回200,表示请求成功。


除了getcode(),还有response.read()来读取下载内容,可简单的获取html数据:

#!/user/bin/python#coding=utf-8import urllib.requestrequest1=urllib.request.urlopen('http://python.org/')html = request1.read()print(html)

request中除了可以传递URL,还可以添加data和头信息http header。

#!/user/bin/python#coding=utf-8import urllib.requestimport urllib.parseurl='http://www.baidu.com'headers={'User-Agent':'Mozilla/4.0 '} #伪装为Mozilla浏览器value={'act':'login','login[email]':'hhh@163.com'}#把字符串转换为gbk编码,还有quoto()与unquoto()方法也是data=urllib.parse.urlencode(value)request=urllib.request.Request(url,data,headers)response=urllib.request.urlopen(request)html=response.read()print(html.decode('utf-8'))


添加特殊情景访问器:

需要用户登录访问的:HTTPCookieProcessor

需要代理访问的:ProxyHandler

使用HTTPS加密的:HTTPSHandler

URL存在相互的自动跳转关系:HTTPRedirectHandler

#!/user/bin/python#coding=utf-8import urllib.requestimport http.cookiejarcj=http.cookiejar.CookieJar()pro=urllib.request.HTTPCookieProcessor(cj)opener=urllib.request.build_opener(pro)urllib.request.install_opener(opener)response=urllib.request.urlopen('http://www.baidu.com')print(response.getcode())

2.关于网页解析器

常见的网页解析器有正则表达式、html.parser、beautiful soup、lxml。

beautiful soup很强大,可以使用其他三种解析器,而且是结构化解析(将DOM节点变为DOMtree)

from bs4 import BeautifulSoup# 创建bs对象soup=BeautifulSoup(     html_doc,        # html文档字符串     "html.parser",   # 解析器    from_encoding="utf8" # 文档编码)#查找所有标签为a的节点soup.find_all('a')#查找所有标签为a,属性为“/view/123.htm”soup.find_all('a',href='/view/123.htm')#查找所有标签为div,class为abc,htmltext为python的节点soup.find_all('div',class_='abc',string='python')#也可以用正则表达式soup.find_all('a',href=re.compile(r'/view/\d+\.htm')) #写了r,反斜线只需要写一个#获取到节点后node=soup.find_all('a')node.namenode['href']node.get_text()

小例子:

html_doc = """<html><head><title>The Dormouse's story</title></head><body><p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;and they lived at the bottom of a well.</p><p class="story">...</p>"""from bs4 import BeautifulSoup# 创建bs对象soup=BeautifulSoup(     html_doc,        # html文档字符串     "html.parser",   # 解析器    from_encoding="utf-8" # 文档编码)print('获取所有链接')links=soup.find_all('a')for link in links:    #提取节点类型,属性值,HTMLtext    print(link.name,link['href'],link.get_text())print('获取Lacie的链接')link_node=soup.find('a',string='Lacie')print(link_node.name,link_node['href'],link_node.get_text())print('获取Lacie的链接,正则')lnnode=soup.find('a',string=re.compile(r'il{1,2}i'))print(lnnode.name,lnnode['href'],lnnode.get_text())




0 0