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()
某些网站利用GET与POST方法访问同一URL时会得到不同的响应;还有一些网站仅支持POST方法进行URL访问若采用GET方法则会收到错误提示
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('http://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}')
总结
通常建议在安装第三方Python库时选择本地安装方式。主要原因在于部分第三方库通过远程下载的方式进行安装,在这种情况下,默认采用远程传输可能会导致较低的下载速度。
网页源代码获取格式多种多样,在实际应用中可以根据需求选择合适的获取方式和资源类型。
#GET方式
html_str = requests.get('网址').content.decode(编码格式,默认UTF-8)
#POST方式 data json
html_str = requests.post('网址',data = data).content.decode()
html_str = requests.post('网址',json = data).content.decode()
全部评论 (0)
还没有任何评论哟~
