4.1 使用Python获取网页源代码 |
您所在的位置:网站首页 › python的源码怎么看 › 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>(.*?)(.*?)(.*?)(.*?) |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |