初学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'<html>\n<head>\n<title>A Useful Page</title>\n</head>\n<body>\n<h1>An Interesting Title</h1>\n<div>\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'<html>\n<head>\n<titl

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值