私信  •  关注

Guy

Guy 最近回复了
6 年前
回复了 Guy 创建的主题 » 如何用css Selenium python选择innerText[duplicate]

使用 css_selector Selenium不支持按文本定位元素(尽管它可以在开发人员工具控制台中工作)。唯一的可能是 xpath

element = "//span[contains(text(), 'Control panel')]"
my_driver.find_element_by_xpath(element)

一个 css selector 控制台也不支持,但JQuery支持它。这个 $('...') 从控制台是 document.querySelector

4 年前
回复了 Guy 创建的主题 » python对象的自定义过滤函数

你可以用 itertools.groupby 按第一个值分组并对结果使用max

from itertools import groupby


class Object:

    def __init__(self, score):
        self.score = score

    def __repr__(self):
        return f'<Object {self.score}>'


pairs = [(1, Object(1)), (1, Object(1)), (3, Object(7)), (9, Object(3)), (9, Object(4))]

filtered_pairs = [max(list(elem), key=lambda x: x[1].score) for grp, elem in groupby(pairs, lambda x: (x[0]))]
print(filtered_pairs)

[(1, <Object 1>), (3, <Object 7>), (9, <Object 4>)]
4 年前
回复了 Guy 创建的主题 » Python,重写继承方法的功能

一个选项是覆盖 plot_gdt_and_triangulation() 在里面 Plot2ndPosition

class Plot2ndPosition(PlotOnMap):

    def __init__(self, lat_lon_a, lat_lon_b, optimal):
        super().__init__(lat_lon_a, lat_lon_b, optimal)

    def plot_gdt_and_triangulation(self):
        folium.Marker(
            location=gdt1,
            popup='GDT 1',
            icon=folium.Icon()
        ).add_to(self.f_map)
        folium.Marker(
            location=uav,
            popup='Target Area.',
            icon=folium.Icon()
        ).add_to(self.f_map)

也可以删除 plot_map() ,它只是打电话 create_map() 图2ndposition 实例调用它。如果有更多的逻辑,则不需要将基类保存为成员,它的所有方法都已经可以从 self

def plot_map(self):
    return self.create_map()

您需要检查是否有任何列表项在url中,而不是url是否在列表中。你可以用 for else

for l in my_list:
    if l in url:
        print('Yes having')
        break
else:
    print('No')

如果列表中的任何项目位于url中,则会打印“是”,如果 if 情况从来没有 true .

密码输入 kasaa() 被处决两次,所以 fetchone() 实际上没有 execute() . 得到 cursor 并用它调用其他函数

def get_multiple_info(self, employees_ids):
    """Get info of multiple Employees in database"""
    cursor = None
    try:
        for employee_id in employees_ids:
            cursor = kasaa()
            cursor.execute(
                "SELECT * FROM ospos_employees WHERE ospos_employees.deleted = 0 AND ospos_employees.person_id = %s ",
                employee_id
            )
            row = cursor.fetchone()
            return row()
    except Exception as e:
        print(e)
    finally:
        cursor.close()
4 年前
回复了 Guy 创建的主题 » 如何在python中从web元素中移除coma?

怎么样 replace(',', '') ? 也不需要两次定位元素

address = driver.find_elements_by_css_selector('.restaurants-detail-overview-cards-LocationOverviewCard__addressLink--1pLK4 ._2wKz--mA .restaurants-detail-overview-cards-LocationOverviewCard__detailLinkText--co3ei')
with open(save,'a',encoding='utf-8') as s:
    if address:
        addresst = address[0].texts.replace(',', '') + '\n'
    else:
        addresst = 'NONE'

    s.write(addresst + '\n')
5 年前
回复了 Guy 创建的主题 » 如何解析陈旧的元素引用-selenium(python)

如果你看看 source code

class element_to_be_clickable(object):
    """ An Expectation for checking an element is visible and enabled such that you can click it."""
    def __init__(self, locator):
        self.locator = locator

    def __call__(self, driver):
        element = visibility_of_element_located(self.locator)(driver)
        if element and element.is_enabled():
            return element
        else:
            return False

这个元素可能以前就过时了 if element and element.is_enabled(): 位于上一行之后( visibility_of_element_located 手柄 StaleElementReferenceException )您可以添加 ignored_exceptions=[StaleElementReferenceException] 减速到 WebDriverWait 解决这个问题

Investment1 = WebDriverWait(driver, 10, ignored_exceptions=[StaleElementReferenceException]).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.menu.menuTopCenter > ul > li:nth-child(3) > a")))

还有几点:

  1. 有预期情况 frame_to_be_available_and_switch_to_it 处理框架
  2. python变量应该都是小写的
  3. 你有代码重复,你可以用函数代替

    options = Options()
    options.add_argument("start-maximized")
    driver = webdriver.Chrome(options=options, 
    executable_path=r'C:/Users/SChogle/Downloads/chromedriver.exe')
    actions = ActionChains(driver)
    
    driver.get("xxxxxxx")
    
    def do_login():
        WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe")))
    
        driver.find_element_by_id("Username").send_keys("xxxxx")
        driver.find_element_by_id("Password").send_keys("xxxxx")
        driver.find_element_by_id("submit_button").click()
    
        driver.switch_to.default_content()
    
    def print_content():
        investment = WebDriverWait(driver, 10, ignored_exceptions=[StaleElementReferenceException]).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.menu.menuTopCenter > ul > li:nth-child(3) > a")))
        actions.move_to_element(investment).perform()
    
        investment_summary = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"li:nth-child(3) > div > div:nth-child(1) > a"))).click()
    
        imp_prov = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#product-UT td.portfolioProductContractFundHeaderValueRight"))).get_attribute('innerHTML').strip()
        print(imp_prov)
    
    do_login()
    print_content()
    driver.find_element_by_css_selector("a#btnLogoff").click()
    
    do_login()
    print_content()
    

编辑:

根据您添加的stacktrace,异常实际上是打开的 actions.move_to_element(Investment1).perform() . 它可以通过简单的循环和重试来解决

tries = 0
while tries < 3:
    try:
        investment = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.menu.menuTopCenter > ul > li:nth-child(3) > a")))
        actions.move_to_element(investment).perform()
        tries = 3
    except StaleElementReferenceException:
        tries += 1