【问题标题】:Extract CSS Selector for an element with Selenium使用 Selenium 提取元素的 CSS 选择器
【发布时间】:2018-08-16 12:54:03
【问题描述】:

对于我的项目,我需要为通过解析找到的给定元素提取 CSS 选择器。我所做的是使用 selenium 导航到一个页面,然后使用 python-beautiful soup 我解析页面并查找是否有任何我需要 CSS 选择器的元素。 例如,我可能会尝试查找 id 为“print”的任何输入标签。

soup.find_all('input', {'id': 'print')})

如果我设法找到这样一个元素,我想提取它的提取物,它是 CSS 选择器,类似于“input#print”。我不仅发现使用 id,还发现使用类和正则表达式的组合。 有什么方法可以实现吗?

【问题讨论】:

  • CSS 选择器用于查找元素。如果您已经可以使用 Beautiful Soup 找到您想要的元素,您还需要 CSS 选择器做什么?
  • @Ian 我首先找到选择器,然后将其与 puppeteer 一起使用。例如,我知道在我的网页中存在一个打印按钮,并且我知道它与打印某些内容相关,所以我假设它的 id 或类名将在其中打印,然后我使用正则表达式查找所有具有 id 的按钮或在其中某处带有 print 的类名。如果我找到它,我需要它的选择器来使用 puppeteer(无头 Chrome)访问它。示例我的程序应该找到按钮,即使它的 id 为“randomtextprintrandom”,因为该 id 有打印。它也可以是一个类名。
  • 您是否只是使用此脚本查找这些选择器一次,以便更轻松地编写您的 Puppeteer 脚本?还是每次使用 Puppeteer 时都会这样做?您实际上是在使用 Puppeteer 与 HTML 文档之外的任何内容(例如浏览器 chrome)进行交互吗?
  • @Ian 我将使用这个脚本来查找选择器,但问题是我必须以相同的形式在多个页面中找到选择器,因此我也会进行交互。
  • 如果这个脚本要执行相同的交互来找到所有的选择器,Puppeteer 还需要做什么?

标签: python css selenium web-scraping beautifulsoup


【解决方案1】:

试试这个。

from scrapy.selector import Selector
from selenium import webdriver

link = "https://example.com"
xpath_desire = "normalize-space(//input[@id = 'print'])"

path1 = "./chromedriver"
driver = webdriver.Chrome(executable_path=path1)
driver.get(link)
temp_test = driver.find_element_by_css_selector("body")
elem = temp_test.get_attribute('innerHTML')


value = Selector(text=elem).xpath(xpath_desire).extract()[0]
print(value)

【讨论】:

    【解决方案2】:

    好的,我对 Python 完全陌生,所以我确信对此有更好的答案,但这是我的两分钱 :)

    import requests
    from bs4 import BeautifulSoup
    
    url = "https://stackoverflow.com/questions/49168556/extract-css-selector-for-
    an-element-with-selenium"
    element = 'a'
    idName = 'nav-questions'
    page = requests.get(url)
    soup = BeautifulSoup(page.content, 'html.parser')
    tags = soup.find_all(element, id = idName)
    
    if tags:
        for tag in tags :
            getClassNames = tag.get('class')
            classNames = ''.join(str('.' + x) for x in getClassNames)
            print element + '#' + idName + classNames
    else:
        print ':('
    

    这将打印如下内容:

    a#nav-questions.-link.js-gps-track
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      • 2012-01-04
      • 2012-05-23
      • 1970-01-01
      • 2018-03-28
      • 2012-08-16
      • 1970-01-01
      相关资源
      最近更新 更多