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

2024-10-06 06:57:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试做一个脚本,阅读crunchyroll的rss并访问最新上传和下载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=请求.get(洛博)“。。一切都像你想象的那样到。但是,如果我使用这个变量。。它不起作用。在

任何帮助都可以谢谢。谢谢你呢


Tags: thetextfromimporthttpread链接link
2条回答

您使用的url是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

看起来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

相关问题 更多 >