Python内置的urllib模块,用于访问网络资源。但是,它用起来比较麻烦,而且,缺少很多实用的高级功能。

它是一个Python第三方库,处理URL资源特别方便。

简单实用

之前格式有问题, 全部删除.

有道翻译案例

import requests
import json

# 得到data并把它转为bytes
key = input("请输入要翻译的内容:")
# 1. 把Form表单数据定义为字典,F12->Form Data
data = {
        "i":key,
        "from":"AUTO",
        "to":"AUTO",
        "smartresult":"dict",
        "client":"fanyideskweb",
        "salt":"15437179202229",
        "sign":"b5fee8d2268e22191d3e03ea884d5666",
        "doctype":"json",
        "version":"2.1",
        "keyfrom":"fanyi.web",
        "action":"FY_BY_REALTIME",
        "typoResult":"false"
    }

# 发请求获响应
# url为抓包抓到的POST的地址,去掉translate_o中的 _o
url = "<http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule>"
headers = {"User-Agent":"Mozilla/5.0"}
# 用requests模块的post方法,data参数为Form表单数据,必须为字典
res = requests.post(url,data=data,headers=headers)
res.encoding = "utf-8"
html = res.text

# 把json格式的字符串转为Python中的字典
r_dict = json.loads(html)
r = r_dict["translateResult"][0][0]["tgt"]
print(r)

附录一

查询本机公网IP

  1. 百度搜索IP

  2. 请求地址:

代理参数 :proxies --> 字典

  1. 获取代理IP的网站

    1. 西刺代理
    2. 快代理
    3. 全网代理
  2. 普通代理 :字典

    proxies = {"协议":"协议://IP地址:端口号"}

    proxies = {"http":"<http://183.129.207.82:11328>"}
    res = requests.get(url,proxies=proies,headers..)
    
  3. 私密代理 :字典

    proxies = {"协议":"协议://用户名:密码@IP:端口"}

    proxies = {"http":"<http://309435365:[email protected]:16816>" }
    

示例

普通代理

import requests
import random

url = "<http://httpbin.org/get>"
#url = "<http://www.baidu.com/>"
headers = {"User-Agent":"Mozilla/5.0"}

# IP代理池
proxyList = [
        {"":""},
        {"":""},
        {"":""},
    ]
proxies = random.choice(proxyList)

res = requests.get(url,proxies=proxies,
                   headers=headers)
res.encoding = "utf-8"
html = res.text
print(html)

私密代理

import requests

#url = "<http://httpbin.org/get>"
url = "<http://www.baidu.com/>"
headers = {"User-Agent":"Mozilla/5.0"}
proxies = {"http":"<http://309435365:[email protected]:16816>"}

res = requests.get(url,proxies=proxies,
                   headers=headers)
res.encoding = "utf-8"
print(res.text)