簡體   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