首页 > 解决方案 > 没有捕捉到 BeautifulSoup 所需的线条

问题描述

我正在使用 BeautifulSoup 从 URL https://www.champlain.edu/current-students搜索“学生登录”类。然后,我想在该类中进一步搜索,如果它包含字符串“用户名”或“密码”,则返回完整的行。我的工作代码返回类中的所有内容,但我没有运气增强它以获取仅包含“用户名”或“密码”的特定行。我已经包含了我当前输出的屏幕截图。任何指导将不胜感激。谢谢!!

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen('https://www.champlain.edu/current-students')
bs = BeautifulSoup(html.read(), 'html.parser')
soup = bs.find(class_='student-login')

print(soup)

电流输出

标签: pythonbeautifulsoup

解决方案


这应该为您提供输入字段:

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen('https://www.champlain.edu/current-students')
bs = BeautifulSoup(html.read(), 'html.parser')

print(bs.select_one('#login-username'))
print(bs.select_one('#login-password'))

这是使用 CSS 选择器,#前面的意思是您正在选择任何具有 id = login-username 的元素,我认为这是您想要的。


推荐阅读