Python写爬虫爬妹子
1.下载数据
有的网站做了反爬的处理,可以添加User-Agent :判断浏览器
self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' # 初始化 headers self.headers = {'User-Agent': self.user_agent}
如果不行,在Chrome上按F12分析请求头、请求体,看需不需要添加别的信息,例如有的网址添加了referer:记住当前网页的来源,那么我们在请求的时候就可以带上。
html = requests.get(url, headers=headers) #没错,就是这么简单
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = {'User-Agent': user_agent} # 注意:form data请求参数 params = 'q&viewFlag=A&sortType=default&searchStyle=&searchRegion=city%3A&searchFansNum=¤tPage=1&pageSize=100' def getHome(): url = 'https://mm.taobao.com/tstar/search/tstar_model.do?_input_charset=utf-8' req = urllib2.Request(url, headers=headers) # decode(’utf - 8’)解码 把其他编码转换成unicode编码 # encode(’gbk’) 编码 把unicode编码转换成其他编码 # ”gbk”.decode(’gbk’).encode(’utf - 8') # unicode = 中文 # gbk = 英文 # utf - 8 = 日文 # 英文一 > 中文一 > 日文,unicode相当于转化器 html = urllib2.urlopen(req, data=params).read().decode('gbk').encode('utf-8') # json转对象 peoples = json.loads(html) for i in peoples['data']['searchDOList']: #去下一个页面获取数据 getUseInfo(i['userId'], i['realName'])
2.解析数据
def getUseInfo(userId, realName): url = 'https://mm.taobao.com/self/aiShow.htm?userId=' + str(userId) req = urllib2.Request(url) html = urllib2.urlopen(req).read().decode('gbk').encode('utf-8') pattern = re.compile('<img.*?src=(.*?)/>', re.S) items = re.findall(pattern, html) x = 0 for item in items: if re.match(r'.*(.jpg")$', item.strip()): tt = 'http:' + re.split('"', item.strip())[1] down_image(tt, x, realName) x = x + 1 print('下载完毕')
正则表达式说明
search:在string中进行搜索,成功返回Match object, 失败返回None, 只匹配一个。
findall:在string中查找所有 匹配成功的组, 即用括号括起来的部分。返回list对象,每个list item是由每个匹配的所有组组成的list。
3.保存数据
def down_image(url, filename, realName): req = urllib2.Request(url=url) folder = 'e:\\images\\%s' % realName if os.path.isdir(folder): pass else: os.makedirs(folder) f = folder + '\\%s.jpg' % filename if not os.path.isfile(f): print f binary_data = urllib2.urlopen(req).read() with open(f, 'wb') as temp_file: temp_file.write(binary_data)
GitHub地址,还有其他网站爬虫,欢迎star:https://github.com/peiniwan/CreeperTest