python - 为什么 Beautifulsoup.find() 没有给出具体结果?
问题描述
我在下面有这段代码,我试图得到'Oswestry,England'作为结果。
label = soup.findall('span',{'class':"ProfileHeaderCard-locationText"})
print(label)
但是,它没有给我一个价值。
这是HMTL代码的样子
<span class="ProfileHeaderCard-locationText u-dir" dir="ltr">
<a data-place-id="5b756a1991aa8648" href="/search?q=place%3A5b756a1991aa8648">Oswestry, England</a>
</span>
当我打印标签时,结果是我在上面发布的 HTML 代码。这 是我的完整代码:
import requests as req
from bs4 import BeautifulSoup
usernames = #list of username
location_list = []
for x in usernames:
url= "https://twitter.com/" + x
try:
html = req.get(url)
except Exception as e:
print("Failed to")
continue
soup = BeautifulSoup(html.text,'html.parser')
try:
label = soup.find('span',{'class':"ProfileHeaderCard-locationText"})
label_formatted = label.string.lstrip()
label_formatted = label_formatted.rstrip()
if label_formatted != "":
location_list.append(label_formatted)
print(x + ' : ' + label_formatted)
else:
print('Not found')
except:
print('Not found')
解决方案
您应该调用find
,而不是find_all
获取单个元素。然后使用.text
属性获取文本内容。
label = soup.find('span',{'class':"ProfileHeaderCard-locationText"})
print(label.text)
推荐阅读
- java - Java 8 对多个对象进行排序
- authentication - CookiePolicyOptions 还是 CookieAuthenticationOptions?
- ruby-on-rails - 在同一页面上获得包含评论集合的帖子后,如何在 RoR 中添加新评论?
- html - HTML 触摸屏图库滑块
- osgi - 将 karaf 从 4.0.4 升级到 4.1.7 后出现 ClassNotFoundException
- java - Spring data JPA:如何使用抽象实体
- php - 使用简码在任何地方显示 WooCommerce 优惠券输入字段
- sap - SAP PowerDesigner - 使用 SQL 更改模型
- linux - 在 linux 中使用 display 命令显示所有 .png 图像
- python - ValueError:字典更新序列元素 #0 的长度为 28;2 是必需的