【问题标题】:Web scraping a p tag without a class using Bs4 and Selenium使用 Bs4 和 Selenium 抓取没有类的 p 标签
【发布时间】:2020-04-18 06:13:59
【问题描述】:

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

enter image description here

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

我希望我的问题很清楚,感谢您抽出宝贵时间。

【问题讨论】:

  • 如果您根本不需要硒,该网址会有所帮助

标签: python html selenium web-scraping beautifulsoup


【解决方案1】:

所需元素是启用JavaScript 的元素,因此要提取文本7:45am-10:50am,您必须为@ 诱导WebDriverWait 所需元素987654323@,您可以使用以下任一Locator Strategies

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

【讨论】:

    【解决方案2】:

    要获得没有类的 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)
    

    【讨论】:

      【解决方案3】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 2021-06-07
        • 2017-09-20
        • 1970-01-01
        • 1970-01-01
        • 2020-09-04
        • 2018-11-08
        • 1970-01-01
        • 2019-02-12
        • 1970-01-01
        相关资源
        最近更新 更多