python - 无法获得文本
问题描述
无法在“表格”中获取跨度文本,谢谢!
from bs4 import BeautifulSoup
import urllib2
url1 = "url"
content1 = urllib2.urlopen(url1).read()
soup = BeautifulSoup(content1,"lxml")
table = soup.findAll("div", {"class" : "iw_component","id":"c1417094965154"})
rows = table.find_all('span',recursive=False)
for row in rows:
print(row.text)
解决方案
table = soup.findAll("div", {"class" : "iw_component","id":"c1417094965154"})
在上面的行中,findAll()
返回一个列表。因此,在下一行中,您将收到错误,因为它需要一个 HTML 字符串。
如果您希望只有一个表,请尝试使用以下代码。只需更换
rows = table.find_all('span',recursive=False)
和
rows = table[0].find_all('span')
如果您希望页面中有多个表,请在表上运行 for 循环,然后在 for 循环内运行其余语句。
此外,为了获得漂亮的输出,您可以将 替换为tabs
空格,如下面的代码所示:
row = row.get_text()
row = row.replace('\t', '')
print(row)
您的最终工作代码是:
from bs4 import BeautifulSoup
import urllib2
url1 = "url"
content1 = urllib2.urlopen(url1).read()
soup = BeautifulSoup(content1,"lxml")
table = soup.findAll("div", {"class" : "iw_component","id":"c1417094965154"})
rows = table[0].find_all('span')
for row in rows:
row_str = row.get_text()
row_str = row_str.replace('\t', '')
print(row_str)
关于recursive=False
参数,如果它设置为 false,它只会在直接子代中找到,在你的情况下不会给出任何结果。
如果只希望Beautiful Soup考虑直子,可以传入
recursive=False
推荐阅读
- c++ - 跳过第一个提示
- django - Django 项目找不到 webpack_loader
- java - 为什么我的方法不将字符串或字符返回给 main?
- angularjs - Ionic 框架:构建提供程序和 api url
- php - 如何允许在 sub.domain.com 上可访问的 domain.com 上创建会话
- vue.js - 如何使用 Axios 将数据从外部文件加载到 Vue
- macos - 使用 pip3 卸载 TensorFlow
- c# - 什么时候在 C# 中回收字符串池?
- apache - 为什么 Apache Shiro 的 [anon] 过滤器不能正常工作?
- ionic-framework - 如何更改 app.component.ts 中的项目?