运行下面代码,运行结果没有保存文件,请帮我找出原因 # -- coding: utf-8 -- import urllib.request import re def getNovertContent(): url = 'http://www.quannovel.com/read/640/' req = urllib.request.Request(url) req.add_header('User-Agent', ' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36') data = urllib.request.urlopen(req).read().decode('gbk') str1 = str(data) # 将网页数据转换为字符串 reg = r'<li><a href="(.?)" title=".?">(.?)</a><li>' reg = re.compile(reg) urls = reg.findall(str1) for url in urls: novel_url = url[0] novel_title = url[1] chapt = urllib.request.urlopen(novel_url).read() chapt_html = chapt.decode('gbk') reg = r'</script> (.?)</script type="text/javascript">' reg = re.compile(reg, re.S) chapt_content = reg.findall(chapt_html) chapt_content = chapt_content[0].replace( " ", "") chapt_content = chapt_content.replace("<br />", "") print("正在保存 %s" % novel_title) with open("{}.txt".format(novel_title), 'w', encoding='utf-8') as f: f.write(chapt_content) getNovertContent()
时间: 2024-02-29 08:54:10 浏览: 79
在这段代码中,正则表达式的模式字符串存在错误。具体来说,第17行的正则表达式模式字符串r'</script> (.?)</script type="text/javascript">' 需要修改为r'</script> (.*?)</script type="text/javascript">',因为小说网站中的章节正文内容前面有四个空格,而不是一个空格。另外,正则表达式中的点号也需要修改为点号加上一个问号,以适配所有可能的字符。修改后的代码如下:
```
# -- coding: utf-8 --
import urllib.request
import re
def getNovertContent():
url = 'http://www.quannovel.com/read/640/'
req = urllib.request.Request(url)
req.add_header('User-Agent', ' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36')
data = urllib.request.urlopen(req).read().decode('gbk')
str1 = str(data) # 将网页数据转换为字符串
reg = r'<li><a href="(.?)" title=".?">(.?)</a><li>'
reg = re.compile(reg)
urls = reg.findall(str1)
for url in urls:
novel_url = url[0]
novel_title = url[1]
chapt = urllib.request.urlopen(novel_url).read()
chapt_html = chapt.decode('gbk')
reg = r'</script> (.*?)</script type="text/javascript">'
reg = re.compile(reg, re.S)
chapt_content = reg.findall(chapt_html)
chapt_content = chapt_content[0].replace(" ", "")
chapt_content = chapt_content.replace("<br />", "")
print("正在保存 %s" % novel_title)
with open("{}.txt".format(novel_title), 'w', encoding='utf-8') as f:
f.write(chapt_content)
getNovertContent()
```
这样就可以正常保存爬取到的小说内容了。
阅读全文