You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在Selenium中使用函数返回值作为另一函数参数时遭遇返回值未被识别的问题

问题分析与解决方案

嘿,我一眼就看出问题出在哪了——你没有接收open_profile函数返回的URL值

在你的discover函数里,你调用了self.open_profile(card),但只是执行了函数,没有把它返回的user_profile_url存到一个变量里。而user_profile_urlopen_profile内部的局部变量,外部(也就是discover函数的作用域)根本访问不到它,所以当你写self.driver.get(user_profile_url)的时候,程序自然不知道这个变量是什么,肯定会报错。

修复后的代码

只需要修改discover函数里的循环部分,把open_profile的返回值赋值给user_profile_url即可:

def discover(self, terms):
    self.open_browser()
    for term in terms:
        self.search(term)
        time.sleep(2)
        html = BeautifulSoup(self.driver.page_source, 'lxml')
        time.sleep(0.5)
        #self.scroll(html)
        cards = html.find_all('div', class_='styles__UserCardInformation-sc-f909fw-5 jEfkYy')
        #print(cards)
        time.sleep(0.5)
        for card in cards:
            # 关键修改:接收函数返回的URL
            user_profile_url = self.open_profile(card)
            self.driver.get(user_profile_url)

你的open_profile函数本身是没问题的,它正确生成并返回了用户主页URL,现在只需要在调用时接住这个返回值就行。

额外优化建议(可选)

为了让代码更健壮,避免因为open_profile返回无效值导致报错,可以加个简单的判断:

for card in cards:
    user_profile_url = self.open_profile(card)
    # 确保URL有效再跳转
    if user_profile_url and user_profile_url.startswith('https://'):
        self.driver.get(user_profile_url)
    else:
        # 可以打印日志或者做其他处理
        print(f"无法获取有效的用户主页URL,跳过该卡片")

内容的提问来源于stack exchange,提问作者MOK_Z

火山引擎 最新活动