python - 我怎样才能使列表理解具有 "or?"

标签 python list

我正在尝试从 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://” 添加为出色地。我需要在列表理解中添加什么才能使这项工作(我试图在一行中完成)?

最佳答案

将元组添加到startwith

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

关于python - 我怎样才能使列表理解具有 "or?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55352306/

相关文章:

R 给定相同维度数据表的列表,生成每个单元格均值的汇总

python - 从等高线列表中删除 opencv 等高线

c# - 在 C# 单元测试中比较两个 List<string[]> 对象

python - 对 TarInfo 列表进行排序

python - 如何在数据库之前格式化变量以避免错误

python - 为数据框中的每个组查找不同的百分位数

python - 如何有条件地替换 pandas 数据框列中的子字符串?

python - 如何从扫描文档中提取垂直标签和值?

list - Dart/Flutter如何基于列表中的值以编程方式过滤ListBuilder

c - 向链表中插入一个元素