python爬虫test

phtyon爬虫注意事项
1.登录必要填表,
比如我一般用firefox+httpfox插件来看看自己到底发送了些什么包
verycd的话需要填username,password,continueURI,fk,login_submit这几项,其中fk是随机生成的(其实不太随机,看上去像是把epoch时间经过简单的编码生成的),需要从网页获取,也就是说得先访问一次网页,用正则表达式等工具截取返回数据中的fk项。continueURI顾名思义可以随便写,login_submit是固定的。
2.某些网站反感爬虫的到访,于是对爬虫一律拒绝请求。这时候我们需要伪装成浏览器,这可以通过修改http包中的header来实现
3…验证码的处理:
简单的验证码:字符个数有限,只使用了简单的平移或旋转加噪音而没有扭曲的,这种还是有可能可以处理的,一般思路是旋转的转回来,噪音去掉,然后划分单个字符,划分好了以后再通过特征提取的方法(例如PCA)降维并生成特征库,然后把验证码和特征库进行比较。
4.gzip/deflate支持
现在的网页普遍支持gzip压缩,这往往可以解决大量传输时间,以VeryCD的主页为例,未压缩版本247K,压缩了以后45K,为原来的1/5。这就意味着抓取速度会快5倍。
然而python的urllib/urllib2默认都不支持压缩,要返回压缩格式,必须在request的header里面写明’accept-encoding’,然后读取response后更要检查header查看是否有’content-encoding’一项来判断是否需要解码,很繁琐琐碎。
5.直接上代码
import urllib.request
import re
import string
data = urllib.request.urlopen(“https://read.douban.com/provider/all”).read()
data=data.decode(“utf-8”)
ret1=’

(.*?)
’ #规定正则表达式读取内容
info=re.compile(ret1).findall(data) #使用compile()函数来将前面的东西转换为正则表达式
for i in info:
print(i) #遍历info中的数据
str_info = str(i) #将info列表中的数据转化为字符类型

with open("出版社信息","a+",encoding="utf-8")as f:
    f.write(str_info)
    f.write('\n')                  #在文件中实现换行操作

1806033 罗耶飞 2019/5/20 17:42:28

import urllib.request
import urllib.parse
import urllib.error
import re

key = ‘女士短裙’
string_key = urllib.parse.quote(key)
old_url = ‘https://s.taobao.com/search?q=’+string_key+’&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20190413&ie=utf8&bcoffset=3&ntoffset=3&p4ppushleft=1%2C48&s=’
zheng = ‘pic_url":"//(.?)"’
head = (‘User-Agent’,‘Mozilla/5.0 (Windows NT 6.3; Win64;x64;rv:66.0) Gecko/20100101 Firefox/66.0’)
opener = urllib.request.build_opener()
opener.addheaders = [head]
urllib.request.install_opener(opener)
for i in range(1,10):
url = old_url + str(i
22) #获取地址
data = opener.open(url).read().decode(‘utf-8’,‘ignore’) #编码格式
data1 = re.compile(zheng).findall(data)
print(data1)
for j in range(0,len(data1)):
try:
url_image = data1[j]
image = “https://”+url_image
flie = ‘E:/python学习/python爬虫/data/’+str(i)+‘中’+str(j)+’.jpg’
urllib.request.urlretrieve(image,flie)
except urllib.error.HTTPError as a:
if hasattr(a,‘code’):
print(a.code)
if hasattr(a,‘reason’):
print(a.reason)

你可能感兴趣的:(python爬虫test)