时间:2022-12-03 12:10:19 | 栏目:Python代码 | 点击:次
import requestsif __name__=='__main__': #step 1:搜索Url url='https://123.sogou.com/' #step 2:发起请求 #get方法会返回一个响应对象 response=requests.get(url=url) #step 3:获取响应数据,text返回的是字符串形式的响应数据 page_text=response.text print(page_text) #step 4:持久化存储 with open('./sogou.html','w',encoding='utf-8') as fp: fp.write(page_text) print("爬取数据结束")import requests if __name__=='__main__': #step 1:搜索Url url='https://123.sogou.com/' #step 2:发起请求 #get方法会返回一个响应对象 response=requests.get(url=url) #step 3:获取响应数据,text返回的是字符串形式的响应数据 page_text=response.text print(page_text) #step 4:持久化存储 with open('./sogou.html','w',encoding='utf-8') as fp: fp.write(page_text) print("爬取数据结束")
import requests if __name__=='__main__': #UA伪装:将对应的User-Agent封装到一个字典中 headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.9 Safari/537.36' } url='https://www.sogou.com/sie?' #处理url携带的参数:封装到字典中 kw=input('enter a word:') param={ 'query':kw } #对指定的url发起的请求对应的url是携带参数的,并且请求过程中处理了参数 response=requests.get(url=url,params=param,headers=headers)#headers是伪装 params输入关键词 page_text=response.text#以文本的形式输出 fileName=kw+'.html'#存储为网页形式 with open(fileName,'w+',encoding='utf-8') as fp: fp.write(page_text)#写入fp print(fileName,"保存成功!!")