鱼C论坛

 找回密码
 立即注册
查看: 1269|回复: 2

[技术交流] python 055 爬虫之隐藏和代理

[复制链接]
发表于 2018-7-31 01:11:29 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 风不会停息 于 2018-9-2 21:21 编辑

1. 服务器通过发送的 HTTP 头中的 User-Agent 来进行识别浏览器与非浏览器,服务器还以 User-Agent 来区分各个浏览器。

2. 在用python写爬虫时, 在需要的时候可以通过设置User-Agent伪装成浏览器访问, 有两种方法:
        1. urllib.request.Request(url, data, headers), 通过传入headers参数来设置User-Agent, headers为一个字典, 可以设置为:
  1. head['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36'
复制代码


        2. 利用add_header() 方法往 Request 对象添加 headers, 例如:
  1. req = urllib.request.Request(url, data)
  2.                 req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36')
复制代码


3. 代理: python使用代理访问服务器主要有一下3个步骤:
        1.创建一个代理处理器ProxyHandler:
        proxy_support = urllib.request.ProxyHandler(),ProxyHandler是一个类,其参数是一个字典:{ '类型':'代理ip:端口号'}
        什么是Handler?Handler也叫作处理器,每个handlers知道如何通过特定协议打开URLs,或者如何处理URL打开时的各个方面,例如HTTP重定向或者HTTP cookies。

        2.定制、创建一个opener:
        opener = urllib.request.build_opener(proxy_support)
        什么是opener?python在打开一个url链接时,就会使用opener。其实,urllib.request.urlopen()函数实际上是使用的是默认的opener,只不过在这里我们需要定制一个opener来指定handler。

        3a.安装opener
        urllib.request.install_opener(opener)
        install_opener 用来创建(全局)默认opener,这个表示调用urlopen将使用你安装的opener。

        3b.调用opener
        opener.open(url)
        该方法可以像urlopen函数那样直接用来获取urls:通常不必调用install_opener,除了为了方便。
  1. import urllib.request
  2. import random

  3. url = "https://www.ip.cn/"

  4. iplist = ['121.43.170.207:3128']

  5. proxy_support = urllib.request.ProxyHandler({'http' : random.choice(iplist)})

  6. opener = urllib.request.build_opener(proxy_support)
  7. opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36')]  #伪装成浏览器访问

  8. urllib.request.install_opener(opener)

  9. response = urllib.request.urlopen(url)

  10. html = response.read().decode('utf-8')

  11. print(html)
复制代码


4. Beautiful Soup 4 模块中文文档: https://www.crummy.com/software/ ... c.zh/index.html#id9

5. 正则表达式介绍和简单应用:
        1. 介绍: http://fishc.com.cn/forum.php?mo ... peid%26typeid%3D403
        2. 简单应用: http://fishc.com.cn/forum.php?mo ... peid%26typeid%3D403

动动手1代码:

  1. import urllib.request
  2. import urllib.parse
  3. import re
  4. from  bs4 import BeautifulSoup

  5. def  main():
  6.     keyword = input("请输入关键词: ")
  7.     string_parameters = {'word' : keyword}
  8.     keyword = urllib.parse.urlencode(string_parameters)
  9.    
  10.     url = "http://baike.baidu.com/search/word?%s" % keyword
  11.     response = urllib.request.urlopen(url)
  12.     html = response.read()

  13.     soup = BeautifulSoup(html, "html.parser")

  14.     for  each in soup.find_all( href = re.compile('item') ):
  15.         content = "".join([each.text])
  16.         url2 = "".join(["http://baike.baidu.com", each['href']])
  17.         response2 = urllib.request.urlopen(url2)
  18.         html2 = response2.read()

  19.         soup2 = BeautifulSoup(html2, "html.parser")

  20.         if  soup2.h2:
  21.             content = "".join([content, soup2.h2.text])
  22.         content = "".join([content, ' -> ', url2])
  23.         print(content)

  24. if  __name__ == "__main__":
  25.     main()
复制代码


动动手2代码:

  1. import urllib.request
  2. import urllib.parse
  3. import re
  4. from  bs4 import BeautifulSoup

  5. def  test_url(soup):
  6.     result = soup.find(text = re.compile("百度百科尚未收录词条"))
  7.     if  result:
  8.         print(result[0 : -1])
  9.         return  False
  10.     else:
  11.         return  True

  12. def  summary(soup):
  13.     word = soup.h1.text
  14.     if  soup.h2:
  15.         word += soup.h2.text
  16.     print(word)

  17.     if  soup.find(class_ = "lemma-summary"):
  18.         print(soup.find(class_ = "lemma-summary").text)

  19. def  get_urls(soup):
  20.     for  each in soup.find_all( href = re.compile('item') ):
  21.         content = "".join([each.text])
  22.         url2 = "".join(["http://baike.baidu.com", each['href']])
  23.         response2 = urllib.request.urlopen(url2)
  24.         html2 = response2.read()
  25.         soup2 = BeautifulSoup(html2, "html.parser")

  26.         if  soup2.h2:
  27.             content = "".join([content, soup2.h2.text])
  28.         content = "".join([content, ' -> ', url2])
  29.         yield content

  30. def  main():
  31.     keyword = input("请输入关键词: ")
  32.     string_parameters = {'word' : keyword}
  33.     keyword = urllib.parse.urlencode(string_parameters)
  34.     url = "http://baike.baidu.com/search/word?%s" % keyword
  35.     response = urllib.request.urlopen(url)
  36.     html = response.read()
  37.     soup = BeautifulSoup(html, "html.parser")

  38.     if  test_url(soup):
  39.         summary(soup)

  40.         command = input("是否打印相关链接(Y / N): ")
  41.         if  command == 'N':
  42.             print("程序结束!")
  43.         elif  command == 'Y':
  44.             print("下面打印相关链接: ")
  45.             each = get_urls(soup)
  46.             while  True:
  47.                 try:
  48.                     for  i in range(10):
  49.                         print(next(each))
  50.                 except  StopIteration:
  51.                     break

  52.                 command = input("输入任意字符将继续打印, 输入a则会打印剩下所有内容(ctrl + c 退出程序), 输入q退出程序: ")
  53.                 if  command == 'q':
  54.                     break
  55.                 elif command == 'a':
  56.                     try:
  57.                         for  i in each:
  58.                             print(i)
  59.                     except  KeyboardInterrupt:
  60.                         print("程序退出!")
  61.                         break
  62.                 else:
  63.                     continue

  64. if  __name__ == "__main__":
  65.     main()
复制代码

评分

参与人数 1荣誉 +3 贡献 +3 收起 理由
xudtrowa + 3 + 3

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-2-21 18:40:53 | 显示全部楼层
楼主 我用你那个代理ip的代码返回的还是自己的ip啊 请问是怎么一回事
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-6 17:06:45 | 显示全部楼层
昼木2333 发表于 2020-2-21 18:40
楼主 我用你那个代理ip的代码返回的还是自己的ip啊 请问是怎么一回事

我也是啊,这是什么问题。。按照小甲鱼的视频来的,还是自己的ip
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-21 05:53

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表