简体   繁体   English

Python Selenium-使用函数在循环中提取内容

[英]Python Selenium - extracting contents using function in a loop

I am trying to scrape the contents using selenium and since the xpaths are similar, i am using a list so that i don't need to write 'find_element_by_xpath'. 我正在尝试使用selenium抓取内容,并且由于xpaths相似,所以我使用的是列表,因此我无需编写“ find_element_by_xpath”。 I wrote a function to get the contents but the contents are not getting extracted. 我编写了一个获取内容的函数,但是没有提取内容。 Here is my code: 这是我的代码:

def find_text(path):
    driver.find_element_by_xpath(path).text

ph_packages= ["PAY_AS_YOU_TALK", "EVENINGS_AND_WEEKEND_EXTRA"]
for i in ph_packages:
    ph_name.append(find_text('//*[@id="productButtonControls_ST_%s"]/label' % i))
    print ph_name

There is no output with this code but when i used the same code without the function, then it is working totally fine. 此代码没有输出,但是当我使用不带该功能的相同代码时,它就可以正常工作。

ph_packages= ["PAY_AS_YOU_TALK", "EVENINGS_AND_WEEKEND_EXTRA"]
for i in ph_packages:
    ph_name.append(driver.find_element_by_xpath('//*[@id="productButtonControls_ST_%s"]/label' % i).text)

I think i am doing some mistake with writing the function. 我认为我在编写函数时犯了一些错误。 Could someone help me with this? 有人可以帮我吗?

That is because your function doesn't return anything 那是因为你的函数没有返回任何东西

def find_text(path):
    driver.find_element_by_xpath(path).text

Should be 应该

def find_text(path):
    return driver.find_element_by_xpath(path).text

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM