鱼C论坛

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

爬百度百科,用代理就报错,不用代理反而能正确响应

[复制链接]
发表于 2019-5-31 18:41:38 | 显示全部楼层 |阅读模式

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

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

x
我的代码如下:
  1. import requests
  2. import re
  3. from bs4 import BeautifulSoup
  4. import random
  5. import urllib.request

  6. # 设置代理
  7. def get_ip(ip_url, headers):   # 随机选择一个代理ip
  8.     web_data = requests.get(ip_url, headers = headers)
  9.     soup = BeautifulSoup(web_data.text, 'lxml')
  10.     trs = soup.find_all('tr')
  11.     ip_list = []    # 所有代理ip
  12.     for i in range(2, len(trs)):
  13.         if '服务器地址' not in trs[i].text:
  14.             ip_info = trs[i]
  15.             tds = ip_info.find_all('td')
  16.             ip_list.append(tds[0].text + ':' + tds[1].text)
  17.     return random.choice(ip_list)

  18. def set_opener(url, headers):
  19.     proxy_handler = urllib.request.ProxyHandler({'http':proxy_ip, 'https':proxy_ip})
  20.     opener = urllib.request.build_opener(proxy_handler)
  21.     request = urllib.request.Request(url, headers = headers)
  22.     urllib.request.install_opener(opener)
  23.     response = urllib.request.urlopen(request)
  24.     html = response.read().decode('utf-8', 'ignore')
  25.     response.close()
  26.     return html


  27. if __name__ == '__main__':
  28.     ip_url = 'https://cn-proxy.com/'
  29.     url = 'https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB'
  30.     headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
  31.     proxy_ip = get_ip(ip_url, headers)
  32.     print(set_opener(url, headers))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-5-31 19:00:56 | 显示全部楼层
代理并不是都是可用的,尤其是免费代理
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-1 01:45:37 From FishC Mobile | 显示全部楼层
代理池cookie池user-agent池这些东西,不需要就不要用,在学习阶段,多是自添麻烦,等可用了相关框架,实际需要时再调用下框架的接口
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-1-16 03:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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