Python爬虫_基础

Python版本3.0+

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

1.关于urllib

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

#!/user/bin/python
#coding=utf-8
import urllib.request

response=urllib.request.urlopen('http://www.baidu.com')
print(response.getcode())

返回200,表示请求成功。


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

#!/user/bin/python
#coding=utf-8
import urllib.request

request1=urllib.request.urlopen('http://python.org/')
html = request1.read()
print(html)

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

#!/user/bin/python
#coding=utf-8
import urllib.request
import urllib.parse

url='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-8
import urllib.request
import http.cookiejar

cj=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.name
node['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())




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值