#!/usr/bin/python # -*- coding:utf-8 -*- import urllib.request import re # html = urllib.request.urlopen("https://xiaoshuo.net/0/745/") # data = html.read() #print(data) # def getUrl(urlData): # print("test") # r = r"[a-zA-Z]+://[^\s]*.html" # pat = re.compile(r) # urls = re.findall(pat,str(urlData)) # print(urls) # # getUrl(data) from lxml.html import fromstring from bs4 import BeautifulSoup import urllib.request import requests import time #给定网址和标题 def getContent(url,title): # html = urllib.request.get(url) # data = html.read().decode() # print(url) first = requests.get(url) if first.status_code!=200: time.sleep(3) #网站服务器可能不行,请求失败就隔3s请求 getContent(url,title) return data = first.content #网页内容 soup = BeautifulSoup(data, "html.parser") #多种解析器,这里选这个就够用了 # print(soup.prettify()) content = soup.find_all("div", attrs={"id": "content"}) # filename = title + ".txt" filename = "文件名称.txt" #文件名称,自己改 filea = open(filename, "a", encoding='utf-8') #追加,把每一章合并成一个txt print(title,file=filea) #输出到文件的内容 print(content, file=filea) print("",file=filea) print(url + " " + title + " 下载保存完毕") #提示该章下载完毕 return def getTitles(url): data = requests.get(url).content soup = BeautifulSoup(data, "html.parser") head = "https://xiaoshuo.net" middle = "/17/17225/" #应该自动截取,但是本来就简单,根据需要写死就行了。 titles = soup.find_all("a") # print(titles) for title in titles: str1 = str(title) if str1.find(middle) != -1: if str1.find("https")!= -1: #过滤一下网页的链接 continue elem = fromstring(str1) url = head + elem.attrib["href"] #这些处理都是根据网页结构弄的 text = elem.text getContent(url, text) time.sleep(2) #脆弱的服务器,不能接收过多过快请求 getTitles("https://xiaoshuo.net/17/17225/") #网址肯定是需要自己改的 #下载完毕,需要自行处理一些格式上的问题,还有编码问题
要实现网页访问,方法也很多,针对这个静态网站,感觉简单的request.get就可以了。
还有就是我用的pycharm运行,开着fiddler好像有什么代理错误,所以还是关闭系统代理服务器下载吧。