gpt4 book ai didi

python - 无法获取 文本

转载 作者:行者123 更新时间:2023-11-28 22:18:17 33 4
gpt4 key购买 nike

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

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

Recursive Argument in find()

If you only want Beautiful Soup to consider direct children, you can pass in recursive=False

关于python - 无法获取 <span></span> 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50638894/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com