在Python中将整数连接到URL时出错
我想要处理一组网址,所以我想把一个数字加到网址中,页面的ID会变化,像这样。
在网址的中间有一个%count%
,但是它似乎不起作用。我该怎么把它加上去呢?
count=2
while (count < pages):
mech = Browser()
url = 'http://www.amazon.com/s/ref=sr_pg_%s'% count %'%s?rh=n%3A2858778011%2Cp_drm_rights%3APurchase%7CRental%2Cn%3A2858905011%2Cp_n_date%3A2693527011&page=3&sort=csrank&ie=UTF8&qid=1403073491'
url = int(raw_input(url))
mech = Browser()
page = mech.open(url)
soup = BeautifulSoup(page)
print url
for thediv in soup.findAll('li',{'class':' ilo2'}):
links = thediv.find('a')
links = links['href']
print links
count = count+1
我遇到了这个错误:
TypeError: not all arguments converted during string formatting
最终的网址格式
http://www.amazon.com/s/ref=sr_pg_2?rh=n%3A2858778011%2Cp_drm_rights%3APurchase%7CRental%2Cn%3A2858905011%2Cp_n_date%3A2693527011&page=3&sort=csrank&ie=UTF8&qid=1403073491
4 个回答
0
与其直接用普通字符串来解析或编辑网址,不如使用专门的模块,urllib2
(或者根据你的Python版本使用urllib
)。
下面是一个简单的例子,使用提问者提供的网址:
from urllib2 import urlparse
original_url = (
"""http://www.amazon.com/s/ref=sr_pg_2?rh=n%3A2858778011%2"""
"""Cp_drm_rights%3APurchase%7CRental%2Cn%3A2858905011%2Cp_n_date"""
"""%3A2693527011&page=3&sort=csrank&ie=UTF8&qid=1403073491""")
parsed = urlparse.urlparse(original_url)
这会返回类似这样的内容:
ParseResult(
scheme='http', netloc='www.amazon.com', path='/s/ref=sr_pg_2',
params='',
query='rh=n%3A2858778011%2Cp_drm_rights%3APurchase%7CRental%2Cn%3A2858905011%2Cp_n_date%3A2693527011&page=3&sort=csrank&ie=UTF8&qid=1403073491', fragment='')
接下来,我们修改网址中的路径部分。
scheme, netloc, path, params, query, fragment = parsed
path = '/s/ref=sr_pg_%d' % (count, )
然后我们将网址“反解析”回来:
new_url = urlparse.urlunparse((scheme, netloc, path, params, query, fragment))
这样我们就得到了一个修改过路径的新网址:
'http://www.amazon.com/s/ref=sr_pg_423?rh=n%3A2858778011%2Cp_drm_rights%3APurchase%7CRental%2Cn%3A2858905011%2Cp_n_date%3A2693527011&page=3&sort=csrank&ie=UTF8&qid=1403073491'
0
如果你想保持字符串的原样(不在里面插入变量的值),问题出在你使用了单引号 '
来包裹一个里面又有单引号的字符串。你可以改用双引号来包裹:
url = "http://www.amazon.com/s/ref=sr_pg_%s'% count %'%s?rh=n%3A2858778011%2Cp_drm_rights%3APurchase%7CRental%2Cn%3A2858905011%2Cp_n_date%3A2693527011&page=3&sort=csrank&ie=UTF8&qid=1403073491"
更好的解决办法是对引号进行转义:
url = 'http://www.amazon.com/s/ref=sr_pg_%s\'% count %\'%s?rh=n%3A2858778011%2Cp_drm_rights%3APurchase%7CRental%2Cn%3A2858905011%2Cp_n_date%3A2693527011&page=3&sort=csrank&ie=UTF8&qid=1403073491'
2
在Python中,%
这个符号的用法并不是你想的那样。
下面是正确的用法:
url = 'http://....../ref=sr_pg_%s?rh=.............' % (count, )
因为你在网址模式中已经使用了%
符号,所以你需要先把它们加倍,这样Python就不会把它们当成占位符来看待:
url = 'http://www.amazon.com/s/ref=sr_pg_%s?rh=n%%3A2858778011%%2Cp_drm_rights%%3APurchase%%7CRental%%2Cn%%3A2858905011%%2Cp_n_date%%3A2693527011&page=3&sort=csrank&ie=UTF8&qid=1403073491' % (count, )
另外,Python有一个专门用来解析和创建网址的模块,叫做urllib,你可以在这里找到它的文档:https://docs.python.org/3.3/library/urllib.parse.html
0
你的字符串中有一些经过URL编码的字符(比如%3A
等)。你可以试试用{}
这种写法:
url = 'http://.....{}...{}...'.format(first_arg, second_arg)
这样你就能看到字符串中其他可能存在的问题了。