python requests.get() InvalidSchema 错误

标签 python python-2.7 python-requests

我是 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”的热门搜索结果!-)

关于python requests.get() InvalidSchema 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28143395/

相关文章:

python - pyqtgraph - 导入错误 : No module named pyqtgraph

python - 将字符串文件转换为所需格式 : replace/with _ except the ones before comma

python - 使用 python-requests 库时,域具体应该用于 NTLM 身份验证?

python - 在 pandas 数据框单元格中插入列表

python - 为什么遍历迭代器比将其转换为列表并查询长度要慢?

python - 强制 Django 在逆向时使用 HTTPS URL

python - 请求与请求 future - 响应时间不准确?

python - 使用 python 'requests' 发送 JSON bool 值

python - 警告 : Expected type [Class Name], 改为 'Dict[str, int]'

python - 计算不规则时间序列数据中值的变化