【问题标题】:How to access particular text in web page source using selenium python?如何使用 selenium python 访问网页源中的特定文本?
【发布时间】:2020-11-02 07:58:27
【问题描述】:

这是HTML源代码:


    <div class="dropdown-popup">
       <a href="/integrations/sources/" class="dropdown-item">Sources</a>
       <a href="/integrations/destinations/" class="dropdown-item">Destinations</a>
       <a href="/integrations/analysis-tools/" class="dropdown-item">Analysis</a>
    </div>

我想访问Sources、 Destinations、Analysis 并将其存储在列表中。

我该怎么做,使用 selenium python?

这是我目前得到的


    from selenium import webdriver
    
    browser = webdriver.Firefox()
    browser.get("http://example.com")
    
    tag_list = i.text.strip() for i in browser.find_elements_by_css_selector("div.dropdown-popup").find_elements_by_tag_name('a')
    print(tag_list)

错误:

AttributeError: 'list' object has no attribute 'find_elements_by_tag_name'

【问题讨论】:

  • [i.text.strip() for i in driver.find_elements_by_css_selector("div.dropdown-popup").find_elements_by_tag_name('a)]
  • tag_list = [i.text.strip() for i in browser.find_elements_by_css_selector("div.dropdown-popup"").find_elements_by_tag_name('a')]。错误:'list' 对象有没有属性“find_elements_by_tag_name”

标签: html python-3.x selenium selenium-webdriver css-selectors


【解决方案1】:
In [41]: from selenium import webdriver
    ...:
    ...: driver = webdriver.Chrome("/Users/bigbounty/Downloads/chromedriver")
    ...: html_content = """
    ...: <html>
    ...:      <head></head>
    ...:      <body>
    ...:        <div class="dropdown-popup">
    ...:        <a href="/integrations/sources/" class="dropdown-item">Sources</a>
    ...:        <a href="/integrations/destinations/" class="dropdown-item">Destinations</a>
    ...:        <a href="/integrations/analysis-tools/" class="dropdown-item">Analysis</a>
    ...:     </div>
    ...:      </body>
    ...: </html>"""

In [42]: driver.get("data:text/html;charset=utf-8,{html_content}".format(html_content=html_content))

In [43]: driver.find_elements_by_css_selector("div.dropdown-popup")
Out[43]: [<selenium.webdriver.remote.webelement.WebElement (session="3dd84e3bc612314090a4105a1658c6fc", element="e92de33a-b219-45da-bc17-0fa06533cc06")>]

In [44]: tag_list = [i.text.strip() for i in driver.find_elements_by_css_selector("div.dropdown-popup")[0].find_elemen
    ...: ts_by_tag_name('a')]

In [45]: tag_list
Out[45]: ['Sources', 'Destinations', 'Analysis']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多