python提取网页数据/爬虫入门第一课

动手做爬虫

from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://movie.douban.com/subject/1292052/')
print(r.text)

用到requests_html,一开始按要求使用的pip install requests_html

1\安装完运行发现报错ModuleNotFoundError: No module named 'requests_html'

在stackoverflow上找到了解决办法:pip3 install requests_html

2\再次运行,发现显示的结果中汉字都是乱码

遂又百度,找到以下代码

首先查看源网页代码使用的编码类型,发现是zh-cmn-Hans

利用request库的功能查看默认输出的编码类型

url = 'https://movie.douban.com/subject/3075287/'

#检测默认输出编码类型
response = session.get(url)
print(response.encoding)

输出结果是utf-8,并不是源网页的编码类型

所以要转换一下,利用request库转换输出结果的编码

def get_html(url):
    try:
        response.encoding = 'zh-cmn-Hans'  # 改变编码
        print(response.encoding)
        html = response.text
        return html
    except:
        print('请求网址出错')

 

最后的代码和输出结果是这样的

from requests_html import HTMLSession
session= HTMLSession()

url = 'https://movie.douban.com/subject/3075287/'

#检测默认输出编码类型
response = session.get(url)
print(response.encoding)  


def get_html(url):
    try:
        response.encoding = 'zh-cmn-Hans'  # 改变编码
        print(response.encoding)
        html = response.text
        return html
    except:
        print('请求网址出错')

print(response.text)

以下省略无数行

 

 

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值