HTTP头部信息的模拟
不少网站为了防止爬虫爬取信息,会根据 浏览器 与 urllib库:HTTP头部请求信息的差别来过滤来自爬虫的请求,我们可以利用HTTP头部信息模拟来解决这个屏蔽的问题
urllib库请求HTTP头部信息
# urllib get方式请求数据response = request.urlopen('http://httpbin.org/get?name=hschen&pass=123456')print(response.read().decode('utf-8'))# {# "args": {# "name": "hschen",# "pass": "123456"# },# "headers": {# "Accept-Encoding": "identity",# "Host": "httpbin.org",# "User-Agent": "Python-urllib/3.6"# },# "origin": "39.184.24.154, 39.184.24.154",# "url": "https://httpbin.org/get?name=hschen&pass=123456"# }
真正浏览器请求HTTP头部信息
{"args": {"name": "hschen","pass": "123456"},"headers": {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3","Accept-Encoding": "gzip, deflate","Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8","Host": "httpbin.org","Upgrade-Insecure-Requests": "1","User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"},"origin": "39.184.24.154, 39.184.24.154","url": "https://httpbin.org/get?name=hschen&pass=123456"}
urllib库模拟HTTP头请求数据
from urllib import request, parseurl = 'http://httpbin.org/post'headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Accept-Language": "zh-CN,zh;q=0.8","Connection": "close","Cookie": "_gauges_unique_hour=1; _gauges_unique_day=1; _gauges_unique_month=1; _gauges_unique_year=1; ""_gauges_unique=1","Referer": "http://httpbin.org/","Upgrade-Insecure-Requests": "1","User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 ""Safari/537.36 LBBROWSER "}dict = {'name': 'value'}data = bytes(parse.urlencode(dict), encoding='utf8')req = request.Request(url=url, data=data, headers=headers, method='POST')response = request.urlopen(req)print(response.read().decode('utf-8'))# {# "args": {},# "data": "",# "files": {},# "form": {# "name": "value"# },# "headers": {# "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",# "Accept-Encoding": "identity",# "Accept-Language": "zh-CN,zh;q=0.8",# "Content-Length": "10",# "Content-Type": "application/x-www-form-urlencoded",# "Cookie": "_gauges_unique_hour=1; _gauges_unique_day=1; _gauges_unique_month=1;# _gauges_unique_year=1; _gauges_unique=1",# "Host": "httpbin.org",# "Referer": "http://httpbin.org/",# "Upgrade-Insecure-Requests": "1",# "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)# Chrome/57.0.2987.98 Safari/537.36 LBBROWSER"# },# "json": null,# "origin": "39.184.24.154, 39.184.24.154",# "url": "https://httpbin.org/post"# }
requests库
第三方库,同样可以实现 urllib库的功能 get()及post()请求且更加方便
pip install requests
get请求
# get请求import requestsurl = 'http://httpbin.org/get'data = {'key': 'hschen', 'value': 'student'}response = requests.get(url, data)print(response.text)# {# "args": {# "key": "hschen",# "value": "student"# },# "headers": {# "Accept": "*/*",# "Accept-Encoding": "gzip, deflate",# "Host": "httpbin.org",# "User-Agent": "python-requests/2.22.0"# },# "origin": "39.184.24.154, 39.184.24.154",# "url": "https://httpbin.org/get?key=hschen&value=student"# }
post请求
import requestsdata = {'key': 'hschen', 'value': 'student'}url = 'http://httpbin.org/post'response = requests.post(url, data)print(response.text)# {# "args": {},# "data": "",# "files": {},# "form": {# "key": "hschen",# "value": "student"# },# "headers": {# "Accept": "*/*",# "Accept-Encoding": "gzip, deflate",# "Content-Length": "24",# "Content-Type": "application/x-www-form-urlencoded",# "Host": "httpbin.org",# "User-Agent": "python-requests/2.22.0"# },# "json": null,# "origin": "39.184.24.154, 39.184.24.154",# "url": "https://httpbin.org/post"# }print(response.json())# {'args': {}, 'data': '', 'files': {}, 'form': {'key': 'hschen', 'value': 'student'}, 'headers': {'Accept': '*/*',# 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '24', 'Content-Type': 'application/x-www-form-urlencoded',# 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.22.0'}, 'json': None, 'origin': '39.184.24.154,# 39.184.24.154', 'url': 'https://httpbin.org/post'}
正则表达式
爬取图片路径
import requestsimport recontent = requests.get('http://www.cnu.cc/discoveryPage/hot-人像').textprint(content)# 有关图片的HTML# <div class="grid-item work-thumbnail"># <a href="http://www.cnu.cc/works/366066" class="thumbnail" target="_blank"># <div class="title"># Little Red Riding Hood# </div># <div class="author"># 鲁子烨# </div># </div># <div class="grid-item work-thumbnail"># <a href="(.*?)".*?title">(.*?)# </div># <div class="author"># 鲁子烨# </div># </div>pattern = re.compile(r'<a href="(.*?)".*?title">(.*?)</div>', re.S) # re.S表示单行模式,将\n当作正常的一个字符串,多行变为一行results = re.findall(pattern, content)print(results)# [('http://www.cnu.cc/selectedPage', '\n 最后的纪念\n '),# ('http://www.cnu.cc/works/366066', '\n Little Red Riding Hood\n# '), ('http://www.cnu.cc/works/364609', '\n IMPETUOUS.\n '),# ('http://www.cnu.cc/works/363572', '\n 安全出口\n '),# ('http://www.cnu.cc/works/360384', '\n “日落前夕。”\n '),# ('http://www.cnu.cc/works/359811', '\n Flora \n '),# ('http://www.cnu.cc/works/359586', '\n 差旅人\n '),# ('http://www.cnu.cc/works/358747', '\n Marry in blue Lover be true\n# '), ('http://www.cnu.cc/works/356574', '\n 童趣or童酷\n '),# ('http://www.cnu.cc/works/356429', '\n 旧照记录册\n '),# ('http://www.cnu.cc/works/355057', '\n 47\n '),# ('http://www.cnu.cc/works/354262', '\n 病鱼枯鹤\n '),# ('http://www.cnu.cc/works/354367', '\n 山涧漫游\n '),# ('http://www.cnu.cc/works/354003', '\n "你知道不知道”\n '),# ('http://www.cnu.cc/works/353410', '\n 秀\n '),# ('http://www.cnu.cc/works/353459', '\n "今生缘不尽”\n '),# ('http://www.cnu.cc/works/351070', '\n "广州森林“\n '),# ('http://www.cnu.cc/works/350775', '\n 天真有邪\n '),# ('http://www.cnu.cc/works/350089', '\n "在初恋结束的那个雨季“\n '),# ('http://www.cnu.cc/works/349722', '\n 丹丹丹\n '),# ('http://www.cnu.cc/works/338160', '\n 《某处》\n '),# ('http://www.cnu.cc/works/336928', '\n 无关痛痒\n '),# ('http://www.cnu.cc/works/336905', '\n 女孩与花\n '),# ('http://www.cnu.cc/works/335746', '\n "摄影里的民谣爱情故事”\n '),# ('http://www.cnu.cc/works/335224', '\n 不渝\n '),# ('http://www.cnu.cc/works/334692', '\n 妖怪也喜欢小朋友啊\n '),# ('http://www.cnu.cc/works/333806', '\n 一颗草莓。\n '),# ('http://www.cnu.cc/works/333607', '\n 住在村里的人\n '),# ('http://www.cnu.cc/works/332291', '\n #On the STREET of daylight. \n# '), ('http://www.cnu.cc/works/332289', '\n 《流浪又自由》\n '),# ('http://www.cnu.cc/works/332090', '\n 黑白肖像\n '),# ('http://www.cnu.cc/works/331443', '\n FRONT风尚周刊 X 吴莫愁\n '),# ('http://www.cnu.cc/works/330503', '\n 安安\n '),# ('http://www.cnu.cc/works/329928', '\n 四十七\n '),# ('http://www.cnu.cc/works/329472', '\n 心裡 \n '),# ('http://www.cnu.cc/works/329030', '\n 阿筱与花童\n '),# ('http://www.cnu.cc/works/328298', '\n 复\n '),# ('http://www.cnu.cc/works/323707', '\n 章若楠\n '),# ('http://www.cnu.cc/works/323792', '\n 遇见了冬天\n '),# ('http://www.cnu.cc/works/323484', '\n 『陌生如你』\n '),# ('http://www.cnu.cc/discoveryPage/hot-%E4%BA%BA%E5%83%8F?page=2', '图片标题1</span>\n\n <div# class="right">\n <span class="icon-a share"></span>\n <span# class="vote"><span class="icon-a"></span><span>投一票</span></span>\n <span class="icon-a# tip-l"></span>\n <span class="icon-a tip-r"></span>\n <div class="float-l">\n# <span class="icon-b close"></span>\n <span class="icon-b big"></span>\n ')]for results in results:url, name = resultsprint(url, re.sub('\s', '', name)) # \s 表示将换行符和制表符转换为 ''# http://www.cnu.cc/selectedPage 最后的纪念# http://www.cnu.cc/works/366066 LittleRedRidingHood# http://www.cnu.cc/works/364609 IMPETUOUS.# http://www.cnu.cc/works/363572 安全出口# http://www.cnu.cc/works/360384 “日落前夕。”# http://www.cnu.cc/works/359811 Flora# http://www.cnu.cc/works/359586 差旅人# http://www.cnu.cc/works/358747 MarryinblueLoverbetrue# http://www.cnu.cc/works/356574 童趣or童酷# http://www.cnu.cc/works/356429 旧照记录册# http://www.cnu.cc/works/355057 47# http://www.cnu.cc/works/354262 病鱼枯鹤# http://www.cnu.cc/works/354367 山涧漫游# http://www.cnu.cc/works/354003 "你知道不知道”# http://www.cnu.cc/works/353410 秀# http://www.cnu.cc/works/353459 "今生缘不尽”# http://www.cnu.cc/works/351070 "广州森林“# http://www.cnu.cc/works/350775 天真有邪# http://www.cnu.cc/works/350089 "在初恋结束的那个雨季“# http://www.cnu.cc/works/349722 丹丹丹# http://www.cnu.cc/works/338160 《某处》# http://www.cnu.cc/works/336928 无关痛痒# http://www.cnu.cc/works/336905 女孩与花# http://www.cnu.cc/works/335746 "摄影里的民谣爱情故事”# http://www.cnu.cc/works/335224 不渝# http://www.cnu.cc/works/334692 妖怪也喜欢小朋友啊# http://www.cnu.cc/works/333806 一颗草莓。# http://www.cnu.cc/works/333607 住在村里的人# http://www.cnu.cc/works/332291 #OntheSTREETofdaylight.# http://www.cnu.cc/works/332289 《流浪又自由》# http://www.cnu.cc/works/332090 黑白肖像# http://www.cnu.cc/works/331443 FRONT风尚周刊X吴莫愁# http://www.cnu.cc/works/330503 安安# http://www.cnu.cc/works/329928 四十七# http://www.cnu.cc/works/329472 心裡# http://www.cnu.cc/works/329030 阿筱与花童# http://www.cnu.cc/works/328298 复# http://www.cnu.cc/works/323707 章若楠# http://www.cnu.cc/works/323792 遇见了冬天# http://www.cnu.cc/works/323484 『陌生如你』# http://www.cnu.cc/discoveryPage/hot-%E4%BA%BA%E5%83%8F?page=2 图片标题1# </span><divclass="right"><spanclass="icon-ashare"></span><spanclass="vote"># <spanclass="icon-a"></span><span>投一票</span></span><spanclass="icon-atip-l"># </span><spanclass="icon-atip-r"></span><divclass="float-l"><spanclass="icon-bclose"># </span><spanclass="icon-bbig"></span>
Beautiful Soup
pip install bs4pip install lxml
from bs4 import BeautifulSouphtml_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>"""soup = BeautifulSoup(html_doc, 'lxml')print(soup.prettify()) # 标准HTML# <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 class="sister" href="http://example.com/elsie" id="link1"># Elsie# </a># ,# <a class="sister" href="http://example.com/lacie" id="link2"># Lacie# </a># and# <a class="sister" href="http://example.com/tillie" id="link3"># Tillie# </a># ;# and they lived at the bottom of a well.# </p># <p class="story"># ...# </p># </body># </html>print(soup.title)# <title>The Dormouse's story</title>print(soup.title.string)# The Dormouse's storyprint(soup.p)# <p class="title"><b>The Dormouse's story</b></p>print(soup.p.string)# The Dormouse's storyprint(soup.p['class'])# ['title']print(soup.a)# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>print(soup.find_all('a'))# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister"# href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie"# id="link3">Tillie</a>]print(soup.find(id="link3"))# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>for link in soup.find_all('a'):print(link.get('href'))# http://example.com/elsie# http://example.com/lacie# http://example.com/tillieprint(soup.get_text())# The Dormouse's story## The Dormouse's story# Once upon a time there were three little sisters; and their names were# Elsie,# Lacie and# Tillie;# and they lived at the bottom of a well.# ...
爬取文字信息
网页请求的 headers 可以在网站加载后按下 F12 键在 Network栏查看详细信息
from bs4 import BeautifulSoupimport requestsheaders = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,""application/signed-exchange;v=b3","Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8","Connection": "close","Cookie": "Hm_lvt_f4d0e3fdf986404a69f8eb8774c076ff=1565151190","Referer": "https://hschen.top","Upgrade-Insecure-Requests": "1","User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) ""Chrome/76.0.3809.100 Mobile Safari/537.36 "}url = 'https://hschen.top'def crawtitle(url):response = requests.get(url, headers=headers)soup = BeautifulSoup(response.text, 'lxml')for title_href in soup.find_all('div', class_='row page'):for title in title_href.find_all('a'):if title.get('title'):print(title.get('title'))# HANCAO's Github repository.# Tumblr personal page.# 微信公众号.# 微博账号.# crawtitle(url)# 翻页for i in range(2, 3):url = 'http://hschen.top/page/' + str(i)crawtitle(url)# HANCAO's Github repository.# Tumblr personal page.# 微信公众号.# 微博账号.
爬取图片信息
爬取图片链接后,还要下载图片
