big_song_82 2021-12-15 13:46 采纳率: 25%
浏览 29
已结题

关于type后bs4对象一些属性出现奇怪问题

问题遇到的现象和发生背景

跟着书里的例子学习bs4,通过向bs4.beautifulSoup()传递一个File对象后,type()其类型。发现问题:

  1. 按照书里讲述,type(exampleSoup)应该得到的是list类,而我返回的是:bs4.element.ResultSet, 请问是书写错了么?
  2. 当我在第二行加入print(exampleFile.read())后再运行,程序就提示我在type(elems[0])的list index out of range越界了。这又是怎么回事儿?
  3. 上面两个问题之间有关联么?
    问题相关代码,请勿粘贴截图
exampleFile = open('example.html')
# print(exampleFile.read())
exampleSoup = bs4.BeautifulSoup(exampleFile,'html.parser')
print(type(exampleSoup))
elems = exampleSoup.select('#author')
print(type(elems)) 
print(len(elems))
print(type(elems[0]))
print(elems[0].getText())
print(str(elems[0]))
print(elems[0].attrs)
运行结果及报错内容

问题1. 第二行返回类型不是书中说的list

<class 'bs4.BeautifulSoup'>
<class 'bs4.element.ResultSet'>
1
<class 'bs4.element.Tag'>
Song Wei
<span id="author">Song Wei</span>
{'id': 'author'}
[Finished in 327ms]

问题2. 加入print(exampleFile.read())后,程序报了list越界错

<html>
<head><title>The Website Title</title></head>
<body>
<p>Download my <strong>Python</strong> book from <a href="http://www.baidu.com">my site</a>.</p>
<p class="slogan">Learn python the easy way!</p>
<p>By <span id="author">Song Wei</span></p>
</body>
</html>Traceback (most recent call last):

<class 'bs4.BeautifulSoup'>
<class 'bs4.element.ResultSet'>
0
  File "D:\chwlsw\py-test\chapter11_web\mapIt.py", line 38, in <module>
    print(type(elems[0]))
IndexError: list index out of range
[Finished in 301ms]


我想要达到的结果

请帮忙勘误,感谢!

  • 写回答

1条回答 默认 最新

  • user-from-future 2021-12-15 14:39
    关注

    正常select后应该返回list,这是select的根源码:

    img

    具体情况可能需要知道你的bs4版本,我的是4.7.1版本的

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 12月24日
  • 已采纳回答 12月16日
  • 创建了问题 12月15日

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。