首页 > 解决方案 > 无法获得文本

问题描述

无法在“表格”中获取跨度文本,谢谢!

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)

标签: pythonbeautifulsoup

解决方案


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,它只会在直接子代中找到,在你的情况下不会给出任何结果。

find() 中的递归参数

如果只希望Beautiful Soup考虑直子,可以传入recursive=False


推荐阅读