知识点:
1.choice() 方法返回一个列表,元组或字符串的随机项。
语法:
import random
random.choice( seq )
2.urlencode构造完整的链接URL
语法:
from urllib.parse import urlencode
args= {'wd':'尚学堂'}
url = "https://www.baidu.com/s?{}".format(urlencode(args))
实例
from urllib import request
from urllib.request import urlopen
from random import choice
from urllib.request import Request
from fake_useragent import UserAgent
#传参方法1
"""
from urllib.parse import quote
url = "https://www.baidu.com/s?wd={}".format(quote("尚学堂"))
"""
#传参方法2
from urllib.parse import urlencode
args= {'wd':'尚学堂'}
url = "https://www.baidu.com/s?{}".format(urlencode(args))
headers={
"User-Agent":UserAgent().random
}
print(url)
request =Request(url,headers=headers)
response = urlopen(request)
info = response.read()
print(info.decode('utf-8'))