下面是我的代码,我正试图得到英国奥斯维斯特里的结果
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')
看起来您正在搜索一个span标记,其class属性与您的查询类完全匹配。由于span有两个类,测试失败,没有返回结果
使用css selectors,您可以尝试以下解决方案:
返回包含指定类的span标记
see also
您应该调用
find
,而不是find_all
来获取单个元素。然后使用.text
属性获取文本内容对于任何有相同问题的人,我都可以通过执行以下操作从html代码中获取innerdata:
label2 = soup.findAll('span',{"class":"ProfileHeaderCard-locationText"})[0].get_text
()相关问题 更多 >
编程相关推荐