【问题标题】:Python requests url link which contains a variable partPython请求包含可变部分的url链接
【发布时间】:2015-07-30 15:36:56
【问题描述】:

我想请求具有以下格式的网址列表,例如:

http://en.wikipedia.org/wiki/Monty_Python/001/

http://en.wikipedia.org/wiki/Monty_Python/002/

....

这些代码 001,...我保存在一个 csv 文件中。

import csv
import requests

inputfile = open('trycode.csv','r')
for row in inputfile:
    url = 'http://en.wikipedia.org/wiki/Monty_Python/'
    source = requests.get(url + row/)

显然它不起作用...如何正确调用这些 url,最后一部分来自 csv 文件?

非常感谢!

【问题讨论】:

  • 除了末尾多出的'/'是语法错误,为什么这个“明显”不起作用?
  • 您的代码抛出异常或运行不正确?
  • 也许你的意思是url + row + '/'?还是'%s%s/' % (url, row)
  • @DanielRoseman 问题是url最后包含一个 / ,所以我不知道怎么写。没有 / ,网址添加不正确。
  • @larsks 是的,你说得对,我现在尝试用 url + row +'/' 代替,但是当我打印 url 链接时,en.wikipedia.org/wiki/Monty_Python/00%A2,而不是 en.wikipedia.org/wiki/Monty_Python/002

标签: python csv url web-scraping python-requests


【解决方案1】:

您的文件实际上使用的是逗号分隔值格式吗?似乎只是一个短字符串,我会使用一个 txt 文件,但这只是我。

在尝试调用之前构建字符串 URL 总是一个好主意...这样您可以先检查它...关闭文件也很重要:

import csv
import requests

inputfile = open('trycode.csv','r')
for row in inputfile:
    url = 'http://en.wikipedia.org/wiki/Monty_Python/' + row
    source = requests.get(url)
inputfile .close()

希望这会有所帮助。

【讨论】:

  • 谢谢!但是当我尝试您的代码时,例如使用行条目“01020”时,我总是得到en.wikipedia.org/wiki/Monty_Python/01020%0A,理想情况下我想要en.wikipedia.org/wiki/Monty_Python/010200,可能是我的文件格式有问题?
  • 看起来 &0A 是一个 URL 编码的换行符...检查您的源文件以确保您有干净的数据,或者在使用每一行的值之前替换 %0A。
  • 谢谢!我会看一下文件,看看它是否是一个干净的 txt 文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-30
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多