首页 > 解决方案 > 如何使列表理解具有“或”?

问题描述

我正在尝试从 Google 搜索中获取链接列表:

def google_word(word):
    headers={'User-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763'}
    url = 'https://google.com/search?q={}'.format(word)
    res= requests.get(url, headers=headers)
    tree= html.fromstring(res.text)
    li = tree.xpath("//a[@href]") #list of links that conatin href
    y = [link.get('href') for link in li if link.get('href').startswith("https://") if "google" not in link.get('href')]

现在,这段代码收集了以 " 开头的正确链接,https://"我想做的也是添加"http://"。我需要在列表理解中添加什么才能使其工作(我试图在一行中完成)?

标签: pythonlist

解决方案


将元组添加到开头

y = [link.get('href') for link in li if link.get('href').startswith(("https://", "http://")) if "google" not in link.get('href')]

推荐阅读