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

本人用的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

你可能感兴趣的:(python爬虫返回none)