使用 Bs4 和 Selenium 在没有类的情况下进行网页抓取 p 标签



我正在尝试网络抓取这个 ->

在此处输入图像描述

HTML 有一个带有类的div 标签。 在这个div 标签中,有另一个div 标签,还有另一个没有类的 p 标签。我的目标是专门获取没有类的孤独p标签,并从中获取文本数据。

到目前为止,这是我的代码->

我没有包括代码的某些导入和其他部分。

html = driver.page_source
time.sleep(.1)
soup = bs.BeautifulSoup(html, 'lxml')
time.sleep(.1)

Class_Details = soup.find_all("div", {"class":"row-fluid data_row primary-row class-info class-not-checked"})
for class_detail in Class_Details:
Class_status = class_detail.find_all("div", {"class":"statusColumn"}) 
Status = Class_status[0].text
class_date = class_detail.find_all("p",{"class":"hide-above-small beforeCollapseShow"})
class_time = class_date[0].text 
The 4 lines above can be ignored they work and accomplish their tasks, the lines below however do not and is what I am asking.
cla = class_detail.find_all("p",{"class":"timeColumn"})
print(cla)
The Output of print(cla) is 
[]
[]
[]
[]
[]
[]
[]

好消息是有 7 个空列表与网站一致,因此它肯定会计算/感知我正在抓取的部分,但我需要输出为文本。

我希望我的问题已经清楚了,并感谢您的时间。

要获取没有类的p标签,请使用CSS 选择器与否定伪类:not()结合使用p

在这里,CSS 选择器可以.timeColumn p:not([class])

# select_one to get first one
p_no_class = class_detail.select_one(".timeColumn p:not([class])").text
print(p_no_class)
# select to get all
all_p_no_class = class_detail.select(".timeColumn p:not([class])")
for p in all_p_no_class:
print(p.text)

另请参阅 CSS 选择器,了解没有类。

输出不打印的原因是您尝试打印的是元素,而不是元素文本。应将代码更改为以下内容:

cla = class_detail.find_all("p",{"class":"timeColumn"})
for item in cla:
print(item.text)

我知道您正在使用BeautifulSoup,但是如果您找不到自己喜欢的BS实现,我还将提供使用Selenium/XPath的解决方案:

elements_list = driver.find_elements_by_xpath("//div[@class='timeColumn'/p]")
for element in elements_list:
print(element.text)

所需的元素是启用 JavaScript 的元素,因此要提取文本7:45 AM - 10:50 AM您必须诱导所需的元素WebDriverWait等待visibility_of_element_located(),您可以使用以下任一定位器策略:

  • 使用XPATH

    print(WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "//div[@class='timeColumn']/div[contains(@id, 'days_data')]/p/a[@class='popover-bottom' and text()='F']//following::p[1]"))).text)
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

相关内容

最新更新