
python爬取头条网页body源代码
来源:
浏览:173
时间:2023-08-04
代码如下:
#本代码作用是:在头条里进行关键字搜索,并打印搜索页面的源代码
#1、首先导入相应的模块
import requests
from bs4 import BeautifulSoup
#2、定义函数:设置请求网址并设置请求头,对网站进行解析
def spider1(kw):
url1="https://www.toutiao.com/search/?keyword=" #设置网站的前半部分为头条的搜索页面
url=url1+kw #设置网站为头条的搜索页面+关键字
headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"} #设置请求头
response=requests.get(url,headers=headers) #对网站进行get请求,并伪装成浏览器进行请求
response.encoding="utf-8" #设置网页的编码为utf-8
html=response.text #将网页请求的源代码赋值给html
soup=BeautifulSoup(html,"lxml")
print(soup.findAll("body")) #读取网页的body代码
#3、对函数进行调用,即打印根据关键字进行查询后的源代码
spider1("python") #调用当参数是python时的spider1函数
运行结果如下图所示:


