Skip to main content
 首页 » 编程设计

python requests.get() InvalidSchema 错误

2025年05月04日15zdz8207

我是 python 的新手,我正在尝试编写一些东西以获得从 Google 的“我感觉很幸运”按钮返回的第一个结果。我有一个包含 100 个项目的列表,我需要它来获取 url。这是我所拥有的:

import requests 
 
with open('2012.txt') as f: 
    lines = f.readlines() 
 
for i in range(0, 100): 
    temp1 = "r'http://www.google.com/search?q=\"" 
    temp2 = "\"&btnI'" 
    temp3 = lines[i] 
    temp3 = temp3[:-1] 
    temp4 = temp1+temp3+temp2 
    print temp4 
    var = requests.get(temp4) 
    print var.url 

现在,如果我打印 temp4 中的值并将其粘贴到 requests.get() 中,它就会按我想要的方式工作。但是,每次我尝试传递 temp4 而不是硬编码字符串时,我都会收到错误消息。

请您参考如下方法:

具体来说,我猜你会得到:

requests.exceptions.InvalidSchema: No connection adapters were found for 'r'http://www.google.com/search?q="foo"&btnI'' 

(除了用其他东西代替 foo:-) -- 请将异常作为您的问题的一部分发布,为什么让我们猜测或需要重现?!

问题显然是前导 r' 确实使字符串成为无效模式(尾随 ' 也无济于事)。

所以,试试像这样的东西:

temp1 = 'http://www.google.com/search?q="' 
temp2 = '"&btnI' 

事情应该会变得更好......具体来说,当我这样做时(仍然使用 'foo' 代替真正的 temp3),我得到了

http://en.wikipedia.org/wiki/Foobar 

这似乎是“foo”的热门搜索结果!-)