设置没有默认数据类型的变量

2024-10-01 04:53:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个函数来解析带有selenium的页面

def get_position_links(start_url, browser):
    """
    Retrieve the position_links 
    """
    position_links = []
    next_page_element = ""
    next_page_attribute = ""

    #kick off
    browser.get(start_url)

    def get_position_links_and_next_page_elememnt_in_the_current_page(position_links):
        ##Get the position_links within the page
        #browser change appropriately with the page change
        nonlocal  next_page_element
        nonlocal  next_page_attribute
        position_elements = browser.find_elements_by_class_name("position_link")  # Retrieve the postions link elements
        #select those only contain python in the title
        position_elements = [p for p in position_elements if "python" in p.text.lower()]
        #position_links as global variable set at the top
        position_links.extend([p.get_attribute("href") for p in position_elements])

        #nonlocal to avoied repeated return
        next_page_element = browser.find_element_by_class_name("pager_next")
        #next_page_attribute for the while flag.
        next_page_attribute = next_page_element.get_attribute("class").strip()

    #handle the start_url
    get_position_links_and_next_page_elememnt_in_the_current_page()

    #Traverse until there's no next pages.
    while not next_page_attribute.endswith("disabled"):
        # time.sleep(random.uniform(1,20))
        next_page_element.click()
        get_position_links_and_next_page_elememnt_in_the_current_page()

    return position_links

在封闭函数中,我声明了next_page_element = ""next_page_attribute = "",我不确定它们的数据类型。你知道吗

但是,我应该为它们随机设置一个数据类型,
如果没有像这样的默认数据类型,如何设置变量

var nextPageElement
var nextPageAttribute 

在Javascript中?你知道吗


Tags: andtheinbrowserurlgetpageposition
2条回答

可以使用此函数查找变量的数据类型。你知道吗

type()

例如

a = 1.0
print(type(a))

Output: <class 'float'>

显式数据类型转换称为“类型转换”

显式数据类型转换的一般形式是

> (required_data_type)(expression)

您可以深入研究一些常用的显式数据类型转换。你知道吗

链接:https://www.datacamp.com/community/tutorials/python-data-type-conversion

我看不出有什么理由在这里使用非局部变量。您应该只返回函数中的值。你知道吗

def get_position_links_and_next_page_elememnt_in_the_current_page(position_links):
    ...
    return next_page_element, next_page_attribute 

next_page_element, next_page_attribute = get_position_links_and_next_page_elememnt_in_the_current_page(position_links)

现在不需要非局部的,不需要预定义元素,甚至不需要嵌套函数。你知道吗

相关问题 更多 >