鱼C论坛

 找回密码
 立即注册
查看: 883|回复: 4

[已解决]文本写入

[复制链接]
发表于 2020-6-10 18:49:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import requests, os
  2. from lxml import etree
  3. from fake_useragent import UserAgent
  4. import time

  5. if not os.path.exists('妖怪'):
  6.     os.mkdir('妖怪')

  7. class goblin(object):
  8.     def __init__(self):
  9.         self.url = "http://www.cbaigui.com/?paged={}"
  10.         ua = UserAgent(verify_ssl=False) #是否跳过证书验证,有些网站需要验证才能访问,但你跳过验证就可以正常访问
  11.         self.headers = {
  12.                 'User-Agent': ua.random, #可生成不同浏览器的UA头,UserAgent().chrome 可生成随机谷歌UA头
  13.                 'Host': 'www.cbaigui.com',
  14.                 'Referer': 'http://www.cbaigui.com /?paged=36'  #Referer说明你从哪个网页跳转过来的
  15.             }

  16.     '''发送请求  获取响应'''

  17.     def get_page(self, url):
  18.         res = requests.get(url=url, headers=self.headers)
  19.         html = res.content.decode("utf-8")
  20.         return html
  21.         '''解析数据'''

  22.     #
  23.     def parse_page(self, html):
  24.         parse_html = etree.HTML(html)
  25.         t = parse_html.xpath('//div[@class="post-inner post-hover"]/h2')
  26.         for i in t:
  27.             goblin_herf = i.xpath('./a/@href')[0].strip()  # 二级页面链接
  28.             name = i.xpath('./a/text()')[0].strip()  # 对应文件夹的名字
  29.             print(name, goblin_herf)
  30.             html2 = self.get_page(goblin_herf)  # 第二个发生请求
  31.             parse_html2 = etree.HTML(html2)
  32.             r = parse_html2.xpath('//div[@class="entry"]/p/text()')
  33.             for rte in r:
  34.                 # print(rte)w
  35.                 try:
  36.                     with open("./妖怪/汇总.txt", "a", encoding='utf-8') as f:
  37.                         f.write(rte)  # 把内容存储到对应名字的文件里
  38.                 except OSError:
  39.                     pass
  40.                 continue

  41.     def main(self):
  42.         startPage = int(input("起始页:"))
  43.         endPage = int(input("终止页:"))
  44.         for page in range(startPage, endPage + 1):
  45.             url = self.url.format(page)
  46.             print(url)
  47.             html = self.get_page(url)
  48.             self.parse_page(html)
  49.             time.sleep(1)
  50.             print("======================第%s页爬取成功!!!!=======================" % page)


  51. if __name__ == '__main__':
  52.     imageSpider = goblin()
  53.     imageSpider.main()
复制代码


第42行,有办法按不同的name在同一个文档中对不同的文本进行换行切分吗?
最佳答案
2020-6-10 19:04:51
jump_p 发表于 2020-6-10 18:58
在一个文档里区分

  1. import requests, os
  2. from lxml import etree
  3. from fake_useragent import UserAgent
  4. import time

  5. if not os.path.exists('妖怪'):
  6.     os.mkdir('妖怪')

  7. class goblin(object):
  8.     def __init__(self):
  9.         self.url = "http://www.cbaigui.com/?paged={}"
  10.         ua = UserAgent(verify_ssl=False) #是否跳过证书验证,有些网站需要验证才能访问,但你跳过验证就可以正常访问
  11.         self.headers = {
  12.                 'User-Agent': ua.random, #可生成不同浏览器的UA头,UserAgent().chrome 可生成随机谷歌UA头
  13.                 'Host': 'www.cbaigui.com',
  14.                 'Referer': 'http://www.cbaigui.com /?paged=36'  #Referer说明你从哪个网页跳转过来的
  15.             }

  16.     '''发送请求  获取响应'''

  17.     def get_page(self, url):
  18.         res = requests.get(url=url, headers=self.headers)
  19.         html = res.content.decode("utf-8")
  20.         return html
  21.         '''解析数据'''

  22.     #
  23.     def parse_page(self, html):
  24.         parse_html = etree.HTML(html)
  25.         t = parse_html.xpath('//div[@class="post-inner post-hover"]/h2')
  26.         for i in t:
  27.             goblin_herf = i.xpath('./a/@href')[0].strip()  # 二级页面链接
  28.             name = i.xpath('./a/text()')[0].strip()  # 对应文件夹的名字
  29.             print(name, goblin_herf)
  30.             html2 = self.get_page(goblin_herf)  # 第二个发生请求
  31.             parse_html2 = etree.HTML(html2)
  32.             r = parse_html2.xpath('//div[@class="entry"]/p/text()')
  33.             r = ''.join(r)
  34.             try:
  35.                 with open("./妖怪/汇总.txt", "a", encoding='utf-8') as f:
  36.                     f.write(f'{name}\n{r}\n')  # 把内容存储到对应名字的文件里
  37.             except OSError:
  38.                 pass
  39.             continue

  40.     def main(self):
  41.         startPage = int(input("起始页:"))
  42.         endPage = int(input("终止页:"))
  43.         for page in range(startPage, endPage + 1):
  44.             url = self.url.format(page)
  45.             print(url)
  46.             html = self.get_page(url)
  47.             self.parse_page(html)
  48.             time.sleep(1)
  49.             print("======================第%s页爬取成功!!!!=======================" % page)


  50. if __name__ == '__main__':
  51.     imageSpider = goblin()
  52.     imageSpider.main()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-6-10 18:52:27 | 显示全部楼层
是不同种文件名嘛?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-6-10 18:58:24 | 显示全部楼层
Twilight6 发表于 2020-6-10 18:52
是不同种文件名嘛?

在一个文档里区分
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-10 19:01:46 | 显示全部楼层
本帖最后由 Stubborn 于 2020-6-10 19:04 编辑

你都是打开一个文本,又没分文件夹,一个文本,你想怎么保存内容?画个文件树出来,看你具体想怎么保存
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-10 19:04:51 | 显示全部楼层    本楼为最佳答案   
jump_p 发表于 2020-6-10 18:58
在一个文档里区分

  1. import requests, os
  2. from lxml import etree
  3. from fake_useragent import UserAgent
  4. import time

  5. if not os.path.exists('妖怪'):
  6.     os.mkdir('妖怪')

  7. class goblin(object):
  8.     def __init__(self):
  9.         self.url = "http://www.cbaigui.com/?paged={}"
  10.         ua = UserAgent(verify_ssl=False) #是否跳过证书验证,有些网站需要验证才能访问,但你跳过验证就可以正常访问
  11.         self.headers = {
  12.                 'User-Agent': ua.random, #可生成不同浏览器的UA头,UserAgent().chrome 可生成随机谷歌UA头
  13.                 'Host': 'www.cbaigui.com',
  14.                 'Referer': 'http://www.cbaigui.com /?paged=36'  #Referer说明你从哪个网页跳转过来的
  15.             }

  16.     '''发送请求  获取响应'''

  17.     def get_page(self, url):
  18.         res = requests.get(url=url, headers=self.headers)
  19.         html = res.content.decode("utf-8")
  20.         return html
  21.         '''解析数据'''

  22.     #
  23.     def parse_page(self, html):
  24.         parse_html = etree.HTML(html)
  25.         t = parse_html.xpath('//div[@class="post-inner post-hover"]/h2')
  26.         for i in t:
  27.             goblin_herf = i.xpath('./a/@href')[0].strip()  # 二级页面链接
  28.             name = i.xpath('./a/text()')[0].strip()  # 对应文件夹的名字
  29.             print(name, goblin_herf)
  30.             html2 = self.get_page(goblin_herf)  # 第二个发生请求
  31.             parse_html2 = etree.HTML(html2)
  32.             r = parse_html2.xpath('//div[@class="entry"]/p/text()')
  33.             r = ''.join(r)
  34.             try:
  35.                 with open("./妖怪/汇总.txt", "a", encoding='utf-8') as f:
  36.                     f.write(f'{name}\n{r}\n')  # 把内容存储到对应名字的文件里
  37.             except OSError:
  38.                 pass
  39.             continue

  40.     def main(self):
  41.         startPage = int(input("起始页:"))
  42.         endPage = int(input("终止页:"))
  43.         for page in range(startPage, endPage + 1):
  44.             url = self.url.format(page)
  45.             print(url)
  46.             html = self.get_page(url)
  47.             self.parse_page(html)
  48.             time.sleep(1)
  49.             print("======================第%s页爬取成功!!!!=======================" % page)


  50. if __name__ == '__main__':
  51.     imageSpider = goblin()
  52.     imageSpider.main()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-21 14:28

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表