这一节主要介绍了requests、beautifulsoup、HTMLParser、数据库编程、登录问题和豆瓣数据爬取。
import json
import requests
from PIL import Image
from io import BytesIO
print('dir(requests):', dir(requests))
url = 'http://www.baidu.com'
r = requests.get(url)
print('r.text:', r.text)
print('r.status_code:', r.status_code)
print('r.encoding:', r.encoding)
dir(requests): ['ConnectTimeout', 'ConnectionError', 'DependencyWarning', 'FileModeWarning', 'HTTPError', 'NullHandler', 'PreparedRequest', 'ReadTimeout', 'Request', 'RequestException', 'Response', 'Session', 'Timeout', 'TooManyRedirects', 'URLRequired', '__author__', '__build__', '__builtins__', '__cached__', '__copyright__', '__doc__', '__file__', '__license__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__title__', '__version__', 'adapters', 'api', 'auth', 'certs', 'codes', 'compat', 'cookies', 'delete', 'exceptions', 'get', 'head', 'hooks', 'logging', 'models', 'options', 'packages', 'patch', 'post', 'put', 'request', 'session', 'sessions', 'status_codes', 'structures', 'utils', 'warnings']
r.text:
r.status_code: 200
r.encoding: ISO-8859-1
# 传递参数:比如http://aaa.com?pageId=1&type=content
params = {'k1':'v1', 'k2':'v2'}
r = requests.get('http://httpbin.org/get', params)
print(r.url)
http://httpbin.org/get?k2=v2&k1=v1
# 二进制数据
r = requests.get('http://i-2.shouji56.com/2015/2/11/23dab5c5-336d-4686-9713-ec44d21958e3.jpg')
image = Image.open(BytesIO(r.content))
image.save('meinv.jpg')
# json处理
r = requests.get('https://github.com/timeline.json')
print(type(r.json))
print(r.text)
{"message":"Hello there, wayfaring stranger. If you’re reading this then you probably didn’t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}
# 原始数据处理,流数据,读一点写一点。数据量大的情况下比较省内存
r = requests.get('http://i-2.shouji56.com/2015/2/11/23dab5c5-336d-4686-9713-ec44d21958e3.jpg', stream = True)
with open('meinv2.jpg', 'wb+') as f:
for chunk in r.iter_content(1024):
f.write(chunk)
# 提交表单
form = {'username':'user', 'password':'pass'}
r = requests.post('http://httpbin.org/post', data = form)
print(r.text)
r = requests.post('http://httpbin.org/post', data = json.dumps(form))
print(r.text)
{
"args": {},
"data": "",
"files": {},
"form": {
"password": "pass",
"username": "user"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "27",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.11.1"
},
"json": null,
"origin": "61.50.181.46",
"url": "http://httpbin.org/post"
}
{
"args": {},
"data": "{\"username\": \"user\", \"password\": \"pass\"}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "40",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.11.1"
},
"json": {
"password": "pass",
"username": "user"
},
"origin": "61.50.181.46",
"url": "http://httpbin.org/post"
}
# cookie
url = 'http://www.baidu.com'
r = requests.get(url)
cookies = r.cookies
for k, v in cookies.get_dict().items():
print(k, v)
cookies = {'c1':'v1', 'c2': 'v2'}
r = requests.get('http://httpbin.org/cookies', cookies = cookies)
print(r.text)
BDORZ 27315
{
"cookies": {
"c1": "v1",
"c2": "v2"
}
}
# 重定向和重定向历史(用的不多)
r = requests.head('http://github.com', allow_redirects = True)
print(r.url)
print(r.status_code)
print(r.history)
https://github.com/
200
[]
# 代理
proxies = {'http': ',,,', 'https': '...'}
r = requests.get('...', proxies = proxies)
程序中使用到了’test.html’,内容如下:
<html><head><title>The Dormouse's storytitle>head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's storyb>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">a>,
<a href="http://example.com/lacie" class="sister" id="link2">Laciea> and
<a href="http://example.com/tillie" class="sister" id="link3">Tilliea>;
and they lived at the bottom of a well.p>
<p class="story">...p>
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('test.html'), "lxml")
print(soup.prettify()) #格式规范化后
The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
,
Lacie
and
Tillie
;
and they lived at the bottom of a well.
...
# Tag
print(type(soup.title))
print(soup.title.name)
print(soup.title)
title
The Dormouse's story
# String
print(type(soup.title.string))
print(soup.title.string)
The Dormouse's story
# Comment
print(type(soup.a.string))
print(soup.a.string)
Elsie
for item in soup.body.contents:
print(item.name)
None
p
None
p
None
p
# CSS查询
print(soup.select('.sister'))
print(soup.select('#link1'))
print(soup.select('head > title'))
a_s = soup.select('a')
for a in a_s:
print(a)
[, Lacie, Tillie]
[]
[The Dormouse's story ]
Lacie
Tillie
markupbase安装方法,直接’pip install’无法安装成功,尝试命令’pip search markupbase’得到包名’micropython-markupbase’,然后直接在网页上下载这个包,下载后里面有一个’_markupbase.py’文件,将文件名开头的’‘去掉后文件复制到python安装目录’\Lib\site-packages’下(如我的电脑’C:\Program Files\Anaconda3\Lib\site-packages’)
from HTMLParser import HTMLParser
# markupbase
class MyParser(HTMLParser): #继承基类来写自己的解析器,Sax模式
def handle_decl(self, decl):
HTMLParser.handle_decl(self, decl)
print('decl %s' % decl)
def handle_starttag(self, tag, attrs):
HTMLParser.handle_starttag(self, tag, attrs)
print('<' + tag + '>')
def handle_endtag(self, tag):
HTMLParser.handle_endtag(self, tag)
print(' + tag + '>')
def handle_data(self, data):
HTMLParser.handle_data(self, data)
print('data %s' % data)
#
def handle_startendtag(self, tag, attrs):
HTMLParser.handle_startendtag(self, tag, attrs)
def handle_comment(self, data):
HTMLParser.handle_comment(self, data)
print('data %s' % data)
def close(self):
HTMLParser.close(self)
print('Close')
demo = MyParser()
demo.feed(open('test.html').read())
demo.close()
data The Dormouse's story
data
data
data The Dormouse's story
data
data Once upon a time there were three little sisters; and their names were
data Elsie
data ,
data Lacie
data and
data Tillie
data ;
and they lived at the bottom of a well.
data
data ...
Close
import sqlite3
conn = sqlite3.connect('test.db')
create_sql = 'create table company(id int primary key not null, emp_name text not null);'
conn.execute(create_sql)
insert_sql = 'insert into company values(?, ?)'
conn.execute(insert_sql, (100, 'LY'))
conn.execute(insert_sql, (200, 'July'))
cursors = conn.execute('select id, emp_name from company')
for row in cursors:
print(row[0], row[1])
conn.close()
100 LY
200 July
import requests
import html5lib
import re
from bs4 import BeautifulSoup
s = requests.Session()
url_login = 'http://accounts.douban.com/login'
formdata = {
'redir':'https://www.douban.com',
'form_email': 'liyanan001@yeah.net',
'form_password': 'xxxxxx',
'login': u'登陆'
}
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'}
r = s.post(url_login, data = formdata, headers = headers)
content = r.text
soup = BeautifulSoup(content, 'html5lib')
captcha = soup.find('img', id = 'captcha_image')
if captcha:
captcha_url = captcha['src']
re_captcha_id = r'
captcha_id = re.findall(re_captcha_id, content)
print(captcha_id)
print(captcha_url)
captcha_text = input('Please input the captcha:')
formdata['captcha-solution'] = captcha_text
formdata['captcha-id'] = captcha_id
r = s.post(url_login, data = formdata, headers = headers)
with open('contacts.txt', 'w+', encoding = 'utf-8') as f:
f.write(r.text)
chrome找cookie:
1.在网页任意地方右击选择’检查’或者按下 shift+ctrl+c打开chrome自带的调试工具,点击Network信息;
2.选择network标签,刷新网页(在打开调试工具的情况下刷新);
3.刷新后’Name’找到该网页url,点击 后右边选择headers,就可以看到当前网页的http头了,在requests headers里有cookie;
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'}
cookies = {'cookie': 'bid=yziFQhTcZIQ; ps=y; ll="108288"; _pk_ref.100001.8cb4=%5B%22%22%2C%22%22%2C1482927892%2C%22https%3A%2F%2Faccounts.douban.com%2Fsafety%2Fbind_resetpassword%3Fconfirmation%3Dd45af5b19bdc537f%26alias%3Dliyanan001%2540yeah.net%22%5D; ue="liyanan001@yeah.net"; dbcl2="76208527:9XkES3vv3uM"; ck=rRSb; __utmt=1; ap=1; push_noty_num=0; push_doumail_num=0; _pk_id.100001.8cb4=ea6d754ff65bcdd2.1474347257.6.1482929703.1481331480.; _pk_ses.100001.8cb4=*; __utma=30149280.2078507961.1473603369.1481331480.1482927892.8; __utmb=30149280.22.10.1482927892; __utmc=30149280; __utmz=30149280.1482927892.8.8.utmcsr=accounts.douban.com|utmccn=(referral)|utmcmd=referral|utmcct=/safety/bind_resetpassword; __utmv=30149280.7620; _vwo_uuid_v2=EB8F16618A0E0BB2959FE9B0E842F251|8cdbe50b30acbb8304a6cfd0bdf4e501'}
url = 'http://www.douban.com'
r = requests.get(url, cookies = cookies, headers = headers)
with open('douban_2.txt', 'wb+') as f:
f.write(r.content)
import requests
from lxml import etree
s = requests.Session()
for id in range(0, 251, 25):
url = 'https://movie.douban.com/top250/?start-' + str(id)
r = s.get(url)
r.encoding = 'utf-8'
root = etree.HTML(r.content)
items = root.xpath('//ol/li/div[@class="item"]')
# print(len(items))
for item in items:
title = item.xpath('./div[@class="info"]//a/span[@class="title"]/text()')
name = title[0].encode('gb2312', 'ignore').decode('gb2312')
# rank = item.xpath('./div[@class="pic"]/em/text()')[0]
rating = item.xpath('.//div[@class="bd"]//span[@class="rating_num"]/text()')[0]
print(name, rating)
肖申克的救赎 9.6
这个杀手不太冷 9.4
霸王别姬 9.5
阿甘正传 9.4
美丽人生 9.5
千与千寻 9.2
辛德勒的名单 9.4
泰坦尼克号 9.2
海上钢琴师 9.2
盗梦空间 9.2
机器人总动员 9.3
三傻大闹宝莱坞 9.1
放牛班的春天 9.2
忠犬八公的故事 9.2
大话西游之大圣娶亲 9.1
龙猫 9.1
教父 9.2
乱世佳人 9.2
楚门的世界 9.0
天堂电影院 9.1
当幸福来敲门 8.9
搏击俱乐部 9.0
触不可及 9.1
十二怒汉 9.3
指环王3:王者无敌 9.1
肖申克的救赎 9.6
这个杀手不太冷 9.4
霸王别姬 9.5
阿甘正传 9.4
美丽人生 9.5
千与千寻 9.2
辛德勒的名单 9.4
泰坦尼克号 9.2
海上钢琴师 9.2
盗梦空间 9.2
机器人总动员 9.3
三傻大闹宝莱坞 9.1
放牛班的春天 9.2
忠犬八公的故事 9.2
大话西游之大圣娶亲 9.1
龙猫 9.1
教父 9.2
乱世佳人 9.2
楚门的世界 9.0
天堂电影院 9.1
当幸福来敲门 8.9
搏击俱乐部 9.0
触不可及 9.1
十二怒汉 9.3
指环王3:王者无敌 9.1
肖申克的救赎 9.6
这个杀手不太冷 9.4
霸王别姬 9.5
阿甘正传 9.4
美丽人生 9.5
千与千寻 9.2
辛德勒的名单 9.4
泰坦尼克号 9.2
海上钢琴师 9.2
盗梦空间 9.2
机器人总动员 9.3
三傻大闹宝莱坞 9.1
放牛班的春天 9.2
忠犬八公的故事 9.2
大话西游之大圣娶亲 9.1
龙猫 9.1
教父 9.2
乱世佳人 9.2
楚门的世界 9.0
天堂电影院 9.1
当幸福来敲门 8.9
搏击俱乐部 9.0
触不可及 9.1
十二怒汉 9.3
指环王3:王者无敌 9.1
肖申克的救赎 9.6
这个杀手不太冷 9.4
霸王别姬 9.5
阿甘正传 9.4
美丽人生 9.5
千与千寻 9.2
辛德勒的名单 9.4
泰坦尼克号 9.2
海上钢琴师 9.2
盗梦空间 9.2
机器人总动员 9.3
三傻大闹宝莱坞 9.1
放牛班的春天 9.2
忠犬八公的故事 9.2
大话西游之大圣娶亲 9.1
龙猫 9.1
教父 9.2
乱世佳人 9.2
楚门的世界 9.0
天堂电影院 9.1
当幸福来敲门 8.9
搏击俱乐部 9.0
触不可及 9.1
十二怒汉 9.3
指环王3:王者无敌 9.1
肖申克的救赎 9.6
这个杀手不太冷 9.4
霸王别姬 9.5
阿甘正传 9.4
美丽人生 9.5
千与千寻 9.2
辛德勒的名单 9.4
泰坦尼克号 9.2
海上钢琴师 9.2
盗梦空间 9.2
机器人总动员 9.3
三傻大闹宝莱坞 9.1
放牛班的春天 9.2
忠犬八公的故事 9.2
大话西游之大圣娶亲 9.1
龙猫 9.1
教父 9.2
乱世佳人 9.2
楚门的世界 9.0
天堂电影院 9.1
当幸福来敲门 8.9
搏击俱乐部 9.0
触不可及 9.1
十二怒汉 9.3
指环王3:王者无敌 9.1
肖申克的救赎 9.6
这个杀手不太冷 9.4
霸王别姬 9.5
阿甘正传 9.4
美丽人生 9.5
千与千寻 9.2
辛德勒的名单 9.4
泰坦尼克号 9.2
海上钢琴师 9.2
盗梦空间 9.2
机器人总动员 9.3
三傻大闹宝莱坞 9.1
放牛班的春天 9.2
忠犬八公的故事 9.2
大话西游之大圣娶亲 9.1
龙猫 9.1
教父 9.2
乱世佳人 9.2
楚门的世界 9.0
天堂电影院 9.1
当幸福来敲门 8.9
搏击俱乐部 9.0
触不可及 9.1
十二怒汉 9.3
指环王3:王者无敌 9.1
肖申克的救赎 9.6
这个杀手不太冷 9.4
霸王别姬 9.5
阿甘正传 9.4
美丽人生 9.5
千与千寻 9.2
辛德勒的名单 9.4
泰坦尼克号 9.2
海上钢琴师 9.2
盗梦空间 9.2
机器人总动员 9.3
三傻大闹宝莱坞 9.1
放牛班的春天 9.2
忠犬八公的故事 9.2
大话西游之大圣娶亲 9.1
龙猫 9.1
教父 9.2
乱世佳人 9.2
楚门的世界 9.0
天堂电影院 9.1
当幸福来敲门 8.9
搏击俱乐部 9.0
触不可及 9.1
十二怒汉 9.3
指环王3:王者无敌 9.1
肖申克的救赎 9.6
这个杀手不太冷 9.4
霸王别姬 9.5
阿甘正传 9.4
美丽人生 9.5
千与千寻 9.2
辛德勒的名单 9.4
泰坦尼克号 9.2
海上钢琴师 9.2
盗梦空间 9.2
机器人总动员 9.3
三傻大闹宝莱坞 9.1
放牛班的春天 9.2
忠犬八公的故事 9.2
大话西游之大圣娶亲 9.1
龙猫 9.1
教父 9.2
乱世佳人 9.2
楚门的世界 9.0
天堂电影院 9.1
当幸福来敲门 8.9
搏击俱乐部 9.0
触不可及 9.1
十二怒汉 9.3
指环王3:王者无敌 9.1
肖申克的救赎 9.6
这个杀手不太冷 9.4
霸王别姬 9.5
阿甘正传 9.4
美丽人生 9.5
千与千寻 9.2
辛德勒的名单 9.4
泰坦尼克号 9.2
海上钢琴师 9.2
盗梦空间 9.2
机器人总动员 9.3
三傻大闹宝莱坞 9.1
放牛班的春天 9.2
忠犬八公的故事 9.2
大话西游之大圣娶亲 9.1
龙猫 9.1
教父 9.2
乱世佳人 9.2
楚门的世界 9.0
天堂电影院 9.1
当幸福来敲门 8.9
搏击俱乐部 9.0
触不可及 9.1
十二怒汉 9.3
指环王3:王者无敌 9.1
肖申克的救赎 9.6
这个杀手不太冷 9.4
霸王别姬 9.5
阿甘正传 9.4
美丽人生 9.5
千与千寻 9.2
辛德勒的名单 9.4
泰坦尼克号 9.2
海上钢琴师 9.2
盗梦空间 9.2
机器人总动员 9.3
三傻大闹宝莱坞 9.1
放牛班的春天 9.2
忠犬八公的故事 9.2
大话西游之大圣娶亲 9.1
龙猫 9.1
教父 9.2
乱世佳人 9.2
楚门的世界 9.0
天堂电影院 9.1
当幸福来敲门 8.9
搏击俱乐部 9.0
触不可及 9.1
十二怒汉 9.3
指环王3:王者无敌 9.1
肖申克的救赎 9.6
这个杀手不太冷 9.4
霸王别姬 9.5
阿甘正传 9.4
美丽人生 9.5
千与千寻 9.2
辛德勒的名单 9.4
泰坦尼克号 9.2
海上钢琴师 9.2
盗梦空间 9.2
机器人总动员 9.3
三傻大闹宝莱坞 9.1
放牛班的春天 9.2
忠犬八公的故事 9.2
大话西游之大圣娶亲 9.1
龙猫 9.1
教父 9.2
乱世佳人 9.2
楚门的世界 9.0
天堂电影院 9.1
当幸福来敲门 8.9
搏击俱乐部 9.0
触不可及 9.1
十二怒汉 9.3
指环王3:王者无敌 9.1