
4.1 使用Python获取网页源代码
1)第三方库的安装
a.在线安装
pip install 第三方库名b.本地安装 下载对应版本的.whl文件,然后cd到文件目录下,通过
pip install xxx.whl 2)使用requests获取网页源代码a. GET方式
import requests html = requests.get('网址')#得到一个Response对象 html_bytes = html.content#属性.content用来显示bytes型网页的源代码 html_str = html_bytes.decode()#属性.decode()用来把bytes型的数据解码为字符串型的数据,默认编码格式UTF-8常见的编码格式 UTF-8、GBK、GB2312、GB18030。以中文可以正常显示为准。 上面的代码可缩减为:
html_str = requests.get('网址').content.decode()b. POST方式 有些网页使用GET和POST方式访问同样的网址,得到的结果不一样。还有些网页只能用POST方式访问,使用GET方式访问返回错误信。 post()方法的格式:
import requests data = {'key1':'value1','key2':'value2'} html_formdata = requests.post('网址',data = data).content.decode() #html_formdata = requests.post('网址',json = data).content.decode()#有些网址提交的内容是json格式3)结合requests与正则表达式 ①提取标题
title = re.search('title>(.*?)<',html,re.S).group(1)②提取正文,并将两端正文使用换行符拼接起来
content_list = re.findall('p>(.*?)<', html_str,re.S) content_str = '\\n'.join(content_list)完整代码如下:
import requests import re html_str = requests.get('exercise.kingname.info/exercise_requests_get.html').content.decode() title = re.search('title>(.*?)<',html,re.S).group(1) content_list = re.findall('p>(.*?)<', html_str,re.S) content_str = '\\n'.join(content_list) print(f'页面标题为:{title}') print(f'页面正文内容为:\\n{content_str}') 总结👁️ 阅读量:0
© 版权声明:本文《4.1 使用Python获取网页源代码》内容均为本站精心整理或网友自愿分享,如需转载请注明原文出处:https://www.zastudy.cn/wen/1686815822a344282.html。