在For循环中使用If创建lambda函数

时间:2020-11-01 10:42:17

标签: python for-loop if-statement lambda

我正在研究Web上的某些抓取工具,并且尝试以此创建lambda函数。

这个想法是,首先我在我创建的BeautifulSoup变量(r_soup)中找到所有“ td”,然后再深入搜索“ a”,然后检查其中有“ JPY”或“取决于经验”的变量文本。那就是我想要的价值:

salary = r_soup.find_all('td')
for s in salary:
    if s.find('a') and 'JPY' in s.text or s.find('a') and 'Depends on experience' in s.text:
        print(s.text.strip())

我已经尝试过了:

salary = list(map(lambda s: s.text if (s.find('a') and 'JPY' in s.text) or (s.find('a') and 'Depends on experience') in s.text ,r_soup.find_all('td')))
salary

但是它不起作用。我对lambda函数了解不多,我一直在网上搜索,但无济于事。谢谢大家的帮助!

1 个答案:

答案 0 :(得分:1)

我建议您尝试列表理解:

[print(s.text.strip()) for s in r_soup.find_all('td') if s.find('a') and 'JPY' in s.text or s.find('a') and 'Depends on experience' in s.text]