【发布时间】:2020-07-22 18:27:58
【问题描述】:
我在下面有这段代码,我试图得到 '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')
【问题讨论】:
-
您使用哪个解析器来解析 HTML 内容?
-
html.parser。尝试过 lxml 但效果不佳
-
您是否检查过您是否使用了正确的汤方法*?
-
使用
.text打印文本 -
该代码适用于大多数 HTML 如下所示的页面: Oswestry, England 但是,如果 HTML 代码看起来像这个 奥斯威斯特,英格兰 我再也买不到 Oswestry England。
标签: python html beautifulsoup html-parsing