我正在尝试从 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/