python_学习爬虫遇到的第二个问题_urllib获取baidu搜索后网页源代码

第二天学习爬虫,学习的是通过urllib.request和urllib.parse获取baidu搜索后网页源代码。

import urllib.request
import urllib.parse
# 请求网址
url='https://www.baidu.com/s?'
# 想要搜索的内容
data={'wd': '周杰伦'}
# 通过urllib.parse.urlencode将data进行url编码
new_data=urllib.parse.urlencode(data)
# 将网址和编码好的内容进行拼接,打印出来的直接放到网址搜索栏就能搜索
url_new=url+new_data
# 刚开始添加了User-Agent,遇到了反爬,又添加Cookie
# value值在请求标头里面找到并填入
headers={'Cookie': '',
         'User-Agent': ''}
# 通过urllib.request.Request订制请求网址所需的内容
request=urllib.request.Request(url=url_new,headers=headers)
# 通过urllib.request.urlopen向网址发出请求
response=urllib.request.urlopen(request)
# 返回请求的内容
contant=response.read().decode('utf-8')
print(contant)

你可能感兴趣的:(python_爬虫,python,学习,爬虫)