繁体   English   中英

使用 Bs4 和 Selenium 在没有类的情况下抓取 ap 标签

[英]Web scraping a p tag without a class using Bs4 and Selenium

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

在此处输入图片说明

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 个空列表与网站一致,因此它肯定在计算/感知我正在抓取的部分,但我需要输出为文本。

我希望我的问题很清楚,谢谢你的时间。

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

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

我知道你在使用 BeautifulSoup,但我也会提供一个使用 Selenium/XPath 的解决方案,以防你找不到你喜欢的 BS 实现:

elements_list = driver.find_elements_by_xpath("//div[@class='timeColumn'/p]")

for element in elements_list:
    print(element.text)

要获取没有类的p标签,请使用.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)

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

  • 使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM