【问题标题】:how to use a variable in requests library of python如何在python的请求库中使用变量
【发布时间】:2015-06-30 04:45:23
【问题描述】:

我正在尝试制作一个脚本来读取 crunchyroll 的 rss 并访问最新上传中的 LINK 并从中下载 subs.. 过程如下: 1.) 阅读来自 RSS 的最新剧集链接。 2.) 转到链接 3.) 在源代码中,查找文本“ssid”。 4.) 获取 ssid 的 6 个字符。 5.) 然后将这些字符附加到此末尾,例如“http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=”并保存 xml 页面。

我的脚本运行到一半...

我的代码:-

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)”中......一切都按预期工作。但是,如果我使用这个变量......它不工作。

任何帮助将不胜感激。谢谢您

【问题讨论】:

    标签: python python-2.7 variables python-requests


    【解决方案1】:

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

    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
    

    【讨论】:

    • 好吧,它消除了错误,但是,问题是 ssid 的值没有在最后的链接中被解析......不知道为什么......
    【解决方案2】:

    您使用的网址是str。你应该使用 Python 的字符串格式化函数。

    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.formatDocs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 2016-11-15
      相关资源
      最近更新 更多