模拟HTTP & HTTPS’ GET & POST请求

HTTP头部信息的模拟

不少网站为了防止爬虫爬取信息,会根据 浏览器 与 urllib库:HTTP头部请求信息的差别来过滤来自爬虫的请求,我们可以利用HTTP头部信息模拟来解决这个屏蔽的问题

urllib库请求HTTP头部信息

  1. # urllib get方式请求数据
  2. response = request.urlopen('http://httpbin.org/get?name=hschen&pass=123456')
  3. print(response.read().decode('utf-8'))
  4. # {
  5. # "args": {
  6. # "name": "hschen",
  7. # "pass": "123456"
  8. # },
  9. # "headers": {
  10. # "Accept-Encoding": "identity",
  11. # "Host": "httpbin.org",
  12. # "User-Agent": "Python-urllib/3.6"
  13. # },
  14. # "origin": "39.184.24.154, 39.184.24.154",
  15. # "url": "https://httpbin.org/get?name=hschen&pass=123456"
  16. # }

真正浏览器请求HTTP头部信息

  1. {
  2. "args": {
  3. "name": "hschen",
  4. "pass": "123456"
  5. },
  6. "headers": {
  7. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
  8. "Accept-Encoding": "gzip, deflate",
  9. "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  10. "Host": "httpbin.org",
  11. "Upgrade-Insecure-Requests": "1",
  12. "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"
  13. },
  14. "origin": "39.184.24.154, 39.184.24.154",
  15. "url": "https://httpbin.org/get?name=hschen&pass=123456"
  16. }

urllib库模拟HTTP头请求数据

  1. from urllib import request, parse
  2. url = 'http://httpbin.org/post'
  3. headers = {
  4. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
  5. "Accept-Language": "zh-CN,zh;q=0.8",
  6. "Connection": "close",
  7. "Cookie": "_gauges_unique_hour=1; _gauges_unique_day=1; _gauges_unique_month=1; _gauges_unique_year=1; "
  8. "_gauges_unique=1",
  9. "Referer": "http://httpbin.org/",
  10. "Upgrade-Insecure-Requests": "1",
  11. "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 "
  12. "Safari/537.36 LBBROWSER "
  13. }
  14. dict = {
  15. 'name': 'value'
  16. }
  17. data = bytes(parse.urlencode(dict), encoding='utf8')
  18. req = request.Request(url=url, data=data, headers=headers, method='POST')
  19. response = request.urlopen(req)
  20. print(response.read().decode('utf-8'))
  21. # {
  22. # "args": {},
  23. # "data": "",
  24. # "files": {},
  25. # "form": {
  26. # "name": "value"
  27. # },
  28. # "headers": {
  29. # "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
  30. # "Accept-Encoding": "identity",
  31. # "Accept-Language": "zh-CN,zh;q=0.8",
  32. # "Content-Length": "10",
  33. # "Content-Type": "application/x-www-form-urlencoded",
  34. # "Cookie": "_gauges_unique_hour=1; _gauges_unique_day=1; _gauges_unique_month=1;
  35. # _gauges_unique_year=1; _gauges_unique=1",
  36. # "Host": "httpbin.org",
  37. # "Referer": "http://httpbin.org/",
  38. # "Upgrade-Insecure-Requests": "1",
  39. # "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
  40. # Chrome/57.0.2987.98 Safari/537.36 LBBROWSER"
  41. # },
  42. # "json": null,
  43. # "origin": "39.184.24.154, 39.184.24.154",
  44. # "url": "https://httpbin.org/post"
  45. # }

requests库

第三方库,同样可以实现 urllib库的功能 get()及post()请求且更加方便

  1. pip install requests

get请求

  1. # get请求
  2. import requests
  3. url = 'http://httpbin.org/get'
  4. data = {'key': 'hschen', 'value': 'student'}
  5. response = requests.get(url, data)
  6. print(response.text)
  7. # {
  8. # "args": {
  9. # "key": "hschen",
  10. # "value": "student"
  11. # },
  12. # "headers": {
  13. # "Accept": "*/*",
  14. # "Accept-Encoding": "gzip, deflate",
  15. # "Host": "httpbin.org",
  16. # "User-Agent": "python-requests/2.22.0"
  17. # },
  18. # "origin": "39.184.24.154, 39.184.24.154",
  19. # "url": "https://httpbin.org/get?key=hschen&value=student"
  20. # }

post请求

  1. import requests
  2. data = {'key': 'hschen', 'value': 'student'}
  3. url = 'http://httpbin.org/post'
  4. response = requests.post(url, data)
  5. print(response.text)
  6. # {
  7. # "args": {},
  8. # "data": "",
  9. # "files": {},
  10. # "form": {
  11. # "key": "hschen",
  12. # "value": "student"
  13. # },
  14. # "headers": {
  15. # "Accept": "*/*",
  16. # "Accept-Encoding": "gzip, deflate",
  17. # "Content-Length": "24",
  18. # "Content-Type": "application/x-www-form-urlencoded",
  19. # "Host": "httpbin.org",
  20. # "User-Agent": "python-requests/2.22.0"
  21. # },
  22. # "json": null,
  23. # "origin": "39.184.24.154, 39.184.24.154",
  24. # "url": "https://httpbin.org/post"
  25. # }
  26. print(response.json())
  27. # {'args': {}, 'data': '', 'files': {}, 'form': {'key': 'hschen', 'value': 'student'}, 'headers': {'Accept': '*/*',
  28. # 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '24', 'Content-Type': 'application/x-www-form-urlencoded',
  29. # 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.22.0'}, 'json': None, 'origin': '39.184.24.154,
  30. # 39.184.24.154', 'url': 'https://httpbin.org/post'}

正则表达式

爬取图片路径

  1. import requests
  2. import re
  3. content = requests.get('http://www.cnu.cc/discoveryPage/hot-人像').text
  4. print(content)
  5. # 有关图片的HTML
  6. # <div class="grid-item work-thumbnail">
  7. # <a href="http://www.cnu.cc/works/366066" class="thumbnail" target="_blank">
  8. # <div class="title">
  9. # Little Red Riding Hood
  10. # </div>
  11. # <div class="author">
  12. # 鲁子烨
  13. # </div>
  14. # </div>
  15. # <div class="grid-item work-thumbnail">
  16. # <a href="(.*?)".*?title">(.*?)
  17. # </div>
  18. # <div class="author">
  19. # 鲁子烨
  20. # </div>
  21. # </div>
  22. pattern = re.compile(r'<a href="(.*?)".*?title">(.*?)</div>', re.S) # re.S表示单行模式,将\n当作正常的一个字符串,多行变为一行
  23. results = re.findall(pattern, content)
  24. print(results)
  25. # [('http://www.cnu.cc/selectedPage', '\n 最后的纪念\n '),
  26. # ('http://www.cnu.cc/works/366066', '\n Little Red Riding Hood\n
  27. # '), ('http://www.cnu.cc/works/364609', '\n IMPETUOUS.\n '),
  28. # ('http://www.cnu.cc/works/363572', '\n 安全出口\n '),
  29. # ('http://www.cnu.cc/works/360384', '\n “日落前夕。”\n '),
  30. # ('http://www.cnu.cc/works/359811', '\n Flora \n '),
  31. # ('http://www.cnu.cc/works/359586', '\n 差旅人\n '),
  32. # ('http://www.cnu.cc/works/358747', '\n Marry in blue Lover be true\n
  33. # '), ('http://www.cnu.cc/works/356574', '\n 童趣or童酷\n '),
  34. # ('http://www.cnu.cc/works/356429', '\n 旧照记录册\n '),
  35. # ('http://www.cnu.cc/works/355057', '\n 47\n '),
  36. # ('http://www.cnu.cc/works/354262', '\n 病鱼枯鹤\n '),
  37. # ('http://www.cnu.cc/works/354367', '\n 山涧漫游\n '),
  38. # ('http://www.cnu.cc/works/354003', '\n "你知道不知道”\n '),
  39. # ('http://www.cnu.cc/works/353410', '\n 秀\n '),
  40. # ('http://www.cnu.cc/works/353459', '\n "今生缘不尽”\n '),
  41. # ('http://www.cnu.cc/works/351070', '\n "广州森林“\n '),
  42. # ('http://www.cnu.cc/works/350775', '\n 天真有邪\n '),
  43. # ('http://www.cnu.cc/works/350089', '\n "在初恋结束的那个雨季“\n '),
  44. # ('http://www.cnu.cc/works/349722', '\n 丹丹丹\n '),
  45. # ('http://www.cnu.cc/works/338160', '\n 《某处》\n '),
  46. # ('http://www.cnu.cc/works/336928', '\n 无关痛痒\n '),
  47. # ('http://www.cnu.cc/works/336905', '\n 女孩与花\n '),
  48. # ('http://www.cnu.cc/works/335746', '\n "摄影里的民谣爱情故事”\n '),
  49. # ('http://www.cnu.cc/works/335224', '\n 不渝\n '),
  50. # ('http://www.cnu.cc/works/334692', '\n 妖怪也喜欢小朋友啊\n '),
  51. # ('http://www.cnu.cc/works/333806', '\n 一颗草莓。\n '),
  52. # ('http://www.cnu.cc/works/333607', '\n 住在村里的人\n '),
  53. # ('http://www.cnu.cc/works/332291', '\n #On the STREET of daylight. \n
  54. # '), ('http://www.cnu.cc/works/332289', '\n 《流浪又自由》\n '),
  55. # ('http://www.cnu.cc/works/332090', '\n 黑白肖像\n '),
  56. # ('http://www.cnu.cc/works/331443', '\n FRONT风尚周刊 X 吴莫愁\n '),
  57. # ('http://www.cnu.cc/works/330503', '\n 安安\n '),
  58. # ('http://www.cnu.cc/works/329928', '\n 四十七\n '),
  59. # ('http://www.cnu.cc/works/329472', '\n 心裡 \n '),
  60. # ('http://www.cnu.cc/works/329030', '\n 阿筱与花童\n '),
  61. # ('http://www.cnu.cc/works/328298', '\n 复\n '),
  62. # ('http://www.cnu.cc/works/323707', '\n 章若楠\n '),
  63. # ('http://www.cnu.cc/works/323792', '\n 遇见了冬天\n '),
  64. # ('http://www.cnu.cc/works/323484', '\n 『陌生如你』\n '),
  65. # ('http://www.cnu.cc/discoveryPage/hot-%E4%BA%BA%E5%83%8F?page=2', '图片标题1</span>\n\n <div
  66. # class="right">\n <span class="icon-a share"></span>\n <span
  67. # class="vote"><span class="icon-a"></span><span>投一票</span></span>\n <span class="icon-a
  68. # tip-l"></span>\n <span class="icon-a tip-r"></span>\n <div class="float-l">\n
  69. # <span class="icon-b close"></span>\n <span class="icon-b big"></span>\n ')]
  70. for results in results:
  71. url, name = results
  72. print(url, re.sub('\s', '', name)) # \s 表示将换行符和制表符转换为 ''
  73. # http://www.cnu.cc/selectedPage 最后的纪念
  74. # http://www.cnu.cc/works/366066 LittleRedRidingHood
  75. # http://www.cnu.cc/works/364609 IMPETUOUS.
  76. # http://www.cnu.cc/works/363572 安全出口
  77. # http://www.cnu.cc/works/360384 “日落前夕。”
  78. # http://www.cnu.cc/works/359811 Flora
  79. # http://www.cnu.cc/works/359586 差旅人
  80. # http://www.cnu.cc/works/358747 MarryinblueLoverbetrue
  81. # http://www.cnu.cc/works/356574 童趣or童酷
  82. # http://www.cnu.cc/works/356429 旧照记录册
  83. # http://www.cnu.cc/works/355057 47
  84. # http://www.cnu.cc/works/354262 病鱼枯鹤
  85. # http://www.cnu.cc/works/354367 山涧漫游
  86. # http://www.cnu.cc/works/354003 "你知道不知道”
  87. # http://www.cnu.cc/works/353410 秀
  88. # http://www.cnu.cc/works/353459 "今生缘不尽”
  89. # http://www.cnu.cc/works/351070 "广州森林“
  90. # http://www.cnu.cc/works/350775 天真有邪
  91. # http://www.cnu.cc/works/350089 "在初恋结束的那个雨季“
  92. # http://www.cnu.cc/works/349722 丹丹丹
  93. # http://www.cnu.cc/works/338160 《某处》
  94. # http://www.cnu.cc/works/336928 无关痛痒
  95. # http://www.cnu.cc/works/336905 女孩与花
  96. # http://www.cnu.cc/works/335746 "摄影里的民谣爱情故事”
  97. # http://www.cnu.cc/works/335224 不渝
  98. # http://www.cnu.cc/works/334692 妖怪也喜欢小朋友啊
  99. # http://www.cnu.cc/works/333806 一颗草莓。
  100. # http://www.cnu.cc/works/333607 住在村里的人
  101. # http://www.cnu.cc/works/332291 #OntheSTREETofdaylight.
  102. # http://www.cnu.cc/works/332289 《流浪又自由》
  103. # http://www.cnu.cc/works/332090 黑白肖像
  104. # http://www.cnu.cc/works/331443 FRONT风尚周刊X吴莫愁
  105. # http://www.cnu.cc/works/330503 安安
  106. # http://www.cnu.cc/works/329928 四十七
  107. # http://www.cnu.cc/works/329472 心裡
  108. # http://www.cnu.cc/works/329030 阿筱与花童
  109. # http://www.cnu.cc/works/328298 复
  110. # http://www.cnu.cc/works/323707 章若楠
  111. # http://www.cnu.cc/works/323792 遇见了冬天
  112. # http://www.cnu.cc/works/323484 『陌生如你』
  113. # http://www.cnu.cc/discoveryPage/hot-%E4%BA%BA%E5%83%8F?page=2 图片标题1
  114. # </span><divclass="right"><spanclass="icon-ashare"></span><spanclass="vote">
  115. # <spanclass="icon-a"></span><span>投一票</span></span><spanclass="icon-atip-l">
  116. # </span><spanclass="icon-atip-r"></span><divclass="float-l"><spanclass="icon-bclose">
  117. # </span><spanclass="icon-bbig"></span>

Beautiful Soup

  1. pip install bs4
  2. pip install lxml
  1. from bs4 import BeautifulSoup
  2. html_doc = """
  3. <html><head><title>The Dormouse's story</title></head>
  4. <body>
  5. <p class="title"><b>The Dormouse's story</b></p>
  6. <p class="story">Once upon a time there were three little sisters; and their names were
  7. <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
  8. <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
  9. <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
  10. and they lived at the bottom of a well.</p>
  11. <p class="story">...</p>
  12. """
  13. soup = BeautifulSoup(html_doc, 'lxml')
  14. print(soup.prettify()) # 标准HTML
  15. # <html>
  16. # <head>
  17. # <title>
  18. # The Dormouse's story
  19. # </title>
  20. # </head>
  21. # <body>
  22. # <p class="title">
  23. # <b>
  24. # The Dormouse's story
  25. # </b>
  26. # </p>
  27. # <p class="story">
  28. # Once upon a time there were three little sisters; and their names were
  29. # <a class="sister" href="http://example.com/elsie" id="link1">
  30. # Elsie
  31. # </a>
  32. # ,
  33. # <a class="sister" href="http://example.com/lacie" id="link2">
  34. # Lacie
  35. # </a>
  36. # and
  37. # <a class="sister" href="http://example.com/tillie" id="link3">
  38. # Tillie
  39. # </a>
  40. # ;
  41. # and they lived at the bottom of a well.
  42. # </p>
  43. # <p class="story">
  44. # ...
  45. # </p>
  46. # </body>
  47. # </html>
  48. print(soup.title)
  49. # <title>The Dormouse's story</title>
  50. print(soup.title.string)
  51. # The Dormouse's story
  52. print(soup.p)
  53. # <p class="title"><b>The Dormouse's story</b></p>
  54. print(soup.p.string)
  55. # The Dormouse's story
  56. print(soup.p['class'])
  57. # ['title']
  58. print(soup.a)
  59. # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
  60. print(soup.find_all('a'))
  61. # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister"
  62. # href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie"
  63. # id="link3">Tillie</a>]
  64. print(soup.find(id="link3"))
  65. # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
  66. for link in soup.find_all('a'):
  67. print(link.get('href'))
  68. # http://example.com/elsie
  69. # http://example.com/lacie
  70. # http://example.com/tillie
  71. print(soup.get_text())
  72. # The Dormouse's story
  73. #
  74. # The Dormouse's story
  75. # Once upon a time there were three little sisters; and their names were
  76. # Elsie,
  77. # Lacie and
  78. # Tillie;
  79. # and they lived at the bottom of a well.
  80. # ...

爬取文字信息

网页请求的 headers 可以在网站加载后按下 F12 键在 Network栏查看详细信息

  1. from bs4 import BeautifulSoup
  2. import requests
  3. headers = {
  4. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,"
  5. "application/signed-exchange;v=b3",
  6. "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  7. "Connection": "close",
  8. "Cookie": "Hm_lvt_f4d0e3fdf986404a69f8eb8774c076ff=1565151190",
  9. "Referer": "https://hschen.top",
  10. "Upgrade-Insecure-Requests": "1",
  11. "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) "
  12. "Chrome/76.0.3809.100 Mobile Safari/537.36 "
  13. }
  14. url = 'https://hschen.top'
  15. def crawtitle(url):
  16. response = requests.get(url, headers=headers)
  17. soup = BeautifulSoup(response.text, 'lxml')
  18. for title_href in soup.find_all('div', class_='row page'):
  19. for title in title_href.find_all('a'):
  20. if title.get('title'):
  21. print(title.get('title'))
  22. # HANCAO's Github repository.
  23. # Tumblr personal page.
  24. # 微信公众号.
  25. # 微博账号.
  26. # crawtitle(url)
  27. # 翻页
  28. for i in range(2, 3):
  29. url = 'http://hschen.top/page/' + str(i)
  30. crawtitle(url)
  31. # HANCAO's Github repository.
  32. # Tumblr personal page.
  33. # 微信公众号.
  34. # 微博账号.

爬取图片信息

爬取图片链接后,还要下载图片

爬虫框架

Scrapy

学习文档

Scrapy stable中文文档