本代码演示通过关键字爬取百度的源代码
将关键字作为get请求的参数传递给服务器,浏览器返回相应的响应内容给用户
代码如下:
#1、导入相应的库import requests#2、对网站进行get请求def gethtml(): #定义获取网页源代码函数gethtml kward=input("请输入关键字:") #要求用户输入关键字,并赋值给kward kwards={'wd':kward} #设置请求参数kwards url="https://www.baidu.com/s" #设置请求网址为百度 headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"} response=requests.get(url,params=kwards,headers=headers) #伪装浏览器对百度网站进行get请求,请求参数为kwards response.encoding=response.apparent_encoding #根据网页内容进行解析编码并赋值给response.encoding print(response.headers) print(response.text)if __name__ == '__main__': gethtml() #调用gethtml函数
代码运行如下图所示: