python爬虫返回none_初学python爬虫,bs4解析后print(bs,h1)返回None的原因和解决方案...

本文主要探讨了在使用Python进行网络爬虫时,遇到BeautifulSoup解析返回None的情况。问题出在尝试读取`html`对象多次导致第二次读取为空。解决方案包括:1) 将数据保存到字符串中再解析;2) 使用`requests`库代替`urllib`。通过这两种方法,可以避免解析问题并得到正确结果。
摘要由CSDN通过智能技术生成

本人用的python3.7,代码在anacoda 3.7版 和自装的bs4 4.9.1都成功测试。

初学爬虫,结果第一个BeautifulSoup的实例就运行失败,print(bs,h1)返回None,但原网页明明就有h1标签。

比如下面的代码。

from bs4 import BeautifulSoup

from urllib.request import urlopen

html = urlopen('http://www.pythonscraping.com/pages/page1.html')

print(html.read())

如果页面OK,返回的是

“b'\n

\nA Useful Page\n\n\n

An Interesting Title

\n
\nLorem ipsum……”这样的。

但我们直接加bs4解析代码就会出问题,比如这样:

from bs4 import BeautifulSoup

from urllib.request import urlopen

html = urlopen('http://www.pythonscraping.com/pages/page1.html')

print(html.read())

#以下是新加的

bs = BeautifulSoup(html, 'html.parser')

print(bs.h1)

返回的是:

“b'\n

\nA Useful Page\n\n\n

An Interesting Title

\n
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值