【问题标题】:Extract data from web page using CSS selector - Selenium Python使用 CSS 选择器从网页中提取数据 - Selenium Python
【发布时间】:2019-02-24 11:59:04
【问题描述】:

我想从戴尔的网站上提取一些我对我的设备感兴趣的日期。 我尝试使用urllib 下载网页,但它受到验证码的保护,我现在无法绕过它。 现在我正在使用 Selenium 打开浏览器,手动解决 capthca,然后自动打开页面并提取日期。 问题是 css 选择器返回了一些奇怪的元素而不是所需的输出

我的代码:

from selenium import webdriver
import time
driver = webdriver.Chrome()


def scrape(codes):
    dates = []
    for i in range(len(codes)):
        driver.get("https://www.dell.com/support/home/us/en/19/product-support/"
                   "servicetag/%s/warranty?ref=captchasuccess" % codes[i])

    # Solve captcha manually
        if i == 0:
            print("You now have 120\" seconds to solve the captcha")
            time.sleep(120)
            print("120\" Passed")
    # Extract data
        expdate = driver.find_element_by_css_selector("#printdivid > div > div.not-annotated.hover > table:nth-child(3) > tbody > tr > td:nth-child(3)")
        print(expdate)
    driver.close()

codes = ['1FMR762', '15FDBG2', '10V8YZ1']
scrape(codes)

预期输出:

June 22, 2018
October 15, 2017
April 19, 2017

给定输出:

<selenium.webdriver.remote.webelement.WebElement (session="d83af0f7a3a9c79307d2058f863a7ecb", element="0.21873872382745052-1")>
<selenium.webdriver.remote.webelement.WebElement (session="d83af0f7a3a9c79307d2058f863a7ecb", element="0.06836824093097027-1")>
<selenium.webdriver.remote.webelement.WebElement (session="d83af0f7a3a9c79307d2058f863a7ecb", element="0.6642161898702734-1")>

【问题讨论】:

    标签: python selenium selenium-chromedriver


    【解决方案1】:

    查看 API 文档,find_element_by_css_selector 函数返回一个 WebElement 对象。见https://selenium-python.readthedocs.io/api.html

    Python and how to get text from Selenium element WebElement object? 中所述,需要在打印之前将网络元素内容转换为字符串。

    因此,将您的线路 print (expdate) 更改为 print (expdate.text) 应该会有所帮助。

    【讨论】:

    • 我把这行改成 print(expdate.get_attribute('innerText')) 因为文本被隐藏了
    • dell.com/support/home/yu/en/yubsdt1/product-support/servicetag/… 当我必须从包含“远程诊断后现场服务”的行中提取日期时,问题就在这里,有没有办法检查?
    • 你当前的程序输出什么?它已经在正确的表格列中了吗?
    • 对于我发布的链接,它输出“2017 年 10 月 15 日”,但应该输出“2019 年 10 月 15 日”,它似乎在右列但不在右行跨度>
    • 您是否尝试将选择器更改为... &gt; table &gt; tbody &gt; tr:nth-child(2) &gt; ...?可以在stackoverflow.com/questions/4494708/… 找到解释
    猜你喜欢
    • 1970-01-01
    • 2021-05-29
    • 2021-12-05
    • 2017-12-04
    • 1970-01-01
    • 2018-08-16
    • 2016-03-06
    • 2019-03-24
    • 2020-03-12
    相关资源
    最近更新 更多