爬虫之中文url解决办法

# 浏览器传中文参数
# 当你抓到包之后
# 发现中文的变了,你不认识了,转码了
# 或者你写一个带有中文的url的python代码
# 例如url = "https://www.baidu.com/s?wd=尚学堂"
# 你会发现机器报错


from urllib.request import Request, urlopen
from urllib.parse import quote

# quote专门用作中文编码的
# print(quote("我爱i"))可以查看中文编码之后的码
url = "https://www.baidu.com/s?wd={}".format(quote("尚学堂"))
headers = {
    # 下面的User-agent首字母大小写不用关心
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"
}
request = Request(url, headers=headers)
response = urlopen(request)
print(response.read().decode())

-------------------------------------------------------

from urllib.request import Request, urlopen
from urllib.parse import urlencode
# 这是比较高级的Useragent
# 它是可以自动动态变换的
# 之前我们用的低级user-agent不需要import库
# 需要我们手动添加一些User-agent
from fake_useragent import UserAgent

args = {
    "wd": "尚学堂",
    "ie": "utf-8"
}
url = "https://www.baidu.com/s?{}".format(urlencode(args))
# 此时输出的url就是带有中文的url的转码后的url
# 你可以直接带到浏览器里使用
print(url)
headers = {
    #随机生成的User-agent
    "User-Agent": UserAgent().random
}
request = Request(url, headers=headers)
response = urlopen(request)
info = response.read()
print(info.decode())

猜你喜欢

转载自blog.csdn.net/qq_43776408/article/details/106819333