n=0
def fetch_title():
from bs4 import BeautifulSoup
reqs = requests.get(URL).text
soup = BeautifulSoup(reqs,"html5lib")
for tag in soup.find_all("meta"):
if tag.get("property", None) == "nv:news:title":
title= tag.get("content", None)
n=n+1
main_title = (n + ". " + title)
return(title)
title1=fetch_title()
os.rename('NAVER_DONLOAD', title1)
到目前为止,我已经尝试了一下,但无济于事,我遇到了2个错误,我将传递txt文件中的url列表,它将解析链接中的数据并将数据保存在特定的文件夹。但我无法重命名该文件夹。
UnboundLocalError Traceback (most recent call last)
<ipython-input-7-2521214d94f6> in <module>()
71 main_title = (n + ". " + title)
72 return(title)
---> 73 title1=fetch_title()
74 os.rename('NAVER_DONLOAD', title1)
<ipython-input-7-2521214d94f6> in fetch_title()
68 if tag.get("property", None) == "nv:news:title":
69 title= tag.get("content", None)
---> 70 n=n+1
71 main_title = (n + ". " + title)
72 return(title)
UnboundLocalError: local variable 'n' referenced before assignment
答案 0 :(得分:1)
您需要使用global
表示法才能使用在函数n
之外定义的全局变量fetch_title()
:
n=0
def fetch_title():
from bs4 import BeautifulSoup
reqs = requests.get(URL).text
soup = BeautifulSoup(reqs,"html5lib")
# Use global instance of n
global n
for tag in soup.find_all("meta"):
if tag.get("property", None) == "nv:news:title":
title= tag.get("content", None)
n=n+1
main_title = (n + ". " + title)
return(title)
title1=fetch_title()
os.rename('NAVER_DONLOAD', title1)
答案 1 :(得分:0)
一个简单的全局n与.join
一起解决了这个问题
这是更新的代码
def fetch_title():
from bs4 import BeautifulSoup
reqs = requests.get(URL).text
soup = BeautifulSoup(reqs,"html5lib")
for tag in soup.find_all("meta"):
n=0
if tag.get("property", None) == "nv:news:title":
title= tag.get("content", None)
n+=1
main_title = '. '.join([str(n),title])
return(main_title)
title1=fetch_title()
os.rename('NAVER_DONLOAD', title1)