首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python的请求库中使用变量

如何在python的请求库中使用变量
EN

Stack Overflow用户
提问于 2015-06-30 04:45:23
回答 2查看 1.2K关注 0票数 0

我正在尝试制作一个脚本,读取crunchyroll的rss并访问最新上传的链接,并从其中下载subs。这个过程如下: 1.)阅读RSS的最新一期链接。2.)转到链接3。)在源代码中,查找文本"ssid“。4.)获取ssid的6个字符。5.)然后在后面添加这些字符,如"id=“,并保存xml页面。

我的剧本半途而废。

我的守则:-

代码语言:javascript
复制
import feedparser
import webbrowser
import os
import subprocess  
import re
import urllib
import urllib2
from urllib2 import urlopen
from bs4 import BeautifulSoup
import requests
import cookielib


feed = feedparser.parse('http://www.crunchyroll.com/rss/anime')  #checks the RSS
url = feed['entries'][0]['link'] + '?p720=1'         # get's the link from latest release and appends some character for the 720p resolution of the link.

# Now, here, I'm writing this URL to a text file and then read from the text file

file = open("newfile.txt", "w")
file.write(url)
file.close()

file = open('newfile.txt', 'r')
#print file.read()
lobo = file.read()
print lobo

# Now, I put the URL that is being read from file in requests to go to the link. Everything works fine till here.

r = requests.get(lobo)
soup = BeautifulSoup(r.text)
print soup.title
webbrowser.open_new_tab(lobo)
subtitles = soup.findAll('span',{'class':'showmedia-subtitle-text'})
for ssid in subtitles:
  x = ssid.find_all('a', limit=1)
for a in x:
  print a['href'][-6:]

xmlLink = 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + a['href'][-6:]
#webbrowser.open_new_tab(xmlLink)
print xmlLink

现在,我得到了在这个xmlLink中没有定义'a‘的错误。

但是,它有一个转折..。如果我把直接的http链接放在"r = requests.get(lobo)“中。如果我使用这个变量的话,一切都像假定的to.But一样。这不管用。

任何帮助都是appreciated.Thank你

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-30 04:57:37

看起来,a变量是在for循环中定义的,但是xmlLink变量不是。尝试将xmlLink行缩进以匹配for循环的缩进级别。例如:

代码语言:javascript
复制
for a in x:
  print a['href'][-6:]

  xmlLink = 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + a['href'][-6:]
  #webbrowser.open_new_tab(xmlLink)
  print xmlLink
票数 0
EN

Stack Overflow用户

发布于 2015-06-30 05:47:47

您使用的url是一个str。您应该使用Python的字符串格式函数。

代码语言:javascript
复制
xmlLinkBase = 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id={0}'
for a in x:
   print a['href'][-6:]
   xmlLink =  xmlLinkBase.format(a['href'][-6:])
   #webbrowser.open_new_tab(xmlLink)
   print xmlLink

str.format 文档

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31129750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档