用到了requests、BeautifulSoup、urllib等,具体代码如下。

# -*- coding: utf-8 -*-
"""
Created on Sat Jul 21 09:13:07 2018
@author: brave_man
email: 1979887709@qq.com 这里先说一个坑。。
页面不存在404的坑。
首先,我们把包含30个投诉的一个页面,称作一个主界面。每一个主界面是包含有30个投诉贴,我们获取每一个投诉贴的超链接,
然后,将获取到的超链接传到getDetails()中,去获取每一个投诉贴的详细内容,包括标题,内容,处理状态等。
当我第一次爬的时候,爬到第十页,显示索引超出了范围,就去找了一下,打开相关投诉贴,显示的是404,页面不存在,程序报错了。
为了增强我们小蜘蛛的健壮性,在获取每个投诉贴详情的时候,先用try语句试一下,当然,前提是你已经确定在获取网页元素的
时候不会出错。
""" import requests
from bs4 import BeautifulSoup
#import json
#from threading import Thread
import urllib
from time import sleep def getDetails(url):
try:
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"}
res = requests.get("{}".format(url), headers = headers)
res.encoding = "GBK"
soup = BeautifulSoup(res.text, "html.parser") try:
content = soup.select(".contentext")[0].text.strip()
except:
content = soup.select(".greyframe")[0].text.split("\n")[7].strip() try:
imgUrl = "http://wz.sun0769.com/" + soup.select(".textpic")[0].img["src"]
imgSaveUrl = "D:\\downloadPhotos" + "\\" + soup.select(".textpic")[0].img["src"][-10:]
urllib.request.urlretrieve(imgUrl, "D:\\downloadPhotos" + "\\" + soup.select(".textpic")[0].img["src"][-10:])
except:
imgSaveUrl = "无图片" try:
status = soup.select(".qgrn")[0].text
except:
try:
status = soup.select(".qblue")[0].text
except:
status = soup.select(".qred")[0].text details = {"Title": soup.select(".tgray14")[0].text[4:-12].strip(),
"Code": soup.select(".tgray14")[0].text[-8:-2],
"Picture": imgSaveUrl,
"Content": content,
"Status": status,
"NetFriend": soup.select(".te12h")[0].text.lstrip(" 网友:")[0:-27],
"Time": soup.select(".te12h")[0].text[-21:-2]}
# jd = json.dumps(details)
# print(type(jd))
try:
with open("saveComplaints.txt", "a") as f:
f.write(str(details))
except:
print("存入失败")
except:
print("页面不存在")
sleep(5) def getA(url):
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"}
res = requests.get("{}".format(url), headers = headers)
res.encoding = "GBK"
soup = BeautifulSoup(res.text, "html.parser")
for i in soup.select(".news14"):
url = i["href"]
getDetails(url) def getPages():
rUrl = "http://wz.sun0769.com/index.php/question/questionType?type=4&page="
for i in range(30):
url = rUrl + str((i - 1) * 30)
getA(url) if __name__ == "__main__":
# getA("http://wz.sun0769.com/index.php/question/questionType?type=4")
# getDetails("http://wz.sun0769.com/html/question/201807/379074.shtml")
getPages()

在编代码的时候,有一些小细节的处理不够熟练,比如文件的读写。下面再搞一搞。

# -*- coding: utf-8 -*-
"""
Created on Sat Jul 21 13:51:40 2018
@author: brave_man
email: 1979887709@qq.com
""" import json try:
with open("saveComplaints.txt", "r") as f:
print("开始读取")
s = f.readline()
# print(s)
except:
print("存入失败") # 将文件中数据读取出来
s1 = s.encode("utf8").decode("unicode-escape")
print(s1) # 转换成json格式
jd = json.dumps(s1)
print(jd) #d = {"name": "张飞", "age": "29"}
#print(str(d))
#jd = json.dumps(d)
#print(jd)
#js = json.loads(jd)
#print(js)

爬虫爬取了前30个页面保存到本地文件中,其实可以考虑用多线程,线程池的方法去分别爬取每一个主页面,这样可能效率会更高一些。至于多线程的部分,还是不太熟练,需要多注意。

python3 requests + BeautifulSoup 爬取阳光网投诉贴详情实例代码的更多相关文章

  1. Python爬虫学习三------requests+BeautifulSoup爬取简单网页

    第一次第一次用MarkDown来写博客,先试试效果吧! 昨天2018俄罗斯世界杯拉开了大幕,作为一个伪球迷,当然也得为世界杯做出一点贡献啦. 于是今天就编写了一个爬虫程序将腾讯新闻下世界杯专题的相关新 ...

  2. 使用requests+BeautifulSoup爬取龙族V小说

    这几天想看龙族最新版本,但是搜索半天发现 没有网站提供 下载, 我又只想下载后离线阅读(写代码已经很费眼睛了).无奈只有自己 爬取了. 这里记录一下,以后想看时,直接运行脚本 下载小说. 这里是从   ...

  3. python 爬虫 requests+BeautifulSoup 爬取巨潮资讯公司概况代码实例

    第一次写一个算是比较完整的爬虫,自我感觉极差啊,代码low,效率差,也没有保存到本地文件或者数据库,强行使用了一波多线程导致数据顺序发生了变化... 贴在这里,引以为戒吧. # -*- coding: ...

  4. requests+BeautifulSoup | 爬取电影天堂全站电影资源

    import requests import urllib.request as ur from bs4 import BeautifulSoup import csv import threadin ...

  5. python 爬虫(一) requests+BeautifulSoup 爬取简单网页代码示例

    以前搞偷偷摸摸的事,不对,是搞爬虫都是用urllib,不过真的是很麻烦,下面就使用requests + BeautifulSoup 爬爬简单的网页. 详细介绍都在代码中注释了,大家可以参阅. # -* ...

  6. requests+beautifulsoup爬取豆瓣图书

    使用Xpath和BeautifulSoup来解析网页可以说真的很简便. import requests from bs4 import BeautifulSoup from random import ...

  7. [实战演练]python3使用requests模块爬取页面内容

    本文摘要: 1.安装pip 2.安装requests模块 3.安装beautifulsoup4 4.requests模块浅析 + 发送请求 + 传递URL参数 + 响应内容 + 获取网页编码 + 获取 ...

  8. Python使用urllib,urllib3,requests库+beautifulsoup爬取网页

    Python使用urllib/urllib3/requests库+beautifulsoup爬取网页 urllib urllib3 requests 笔者在爬取时遇到的问题 1.结果不全 2.'抓取失 ...

  9. python爬取当当网的书籍信息并保存到csv文件

    python爬取当当网的书籍信息并保存到csv文件 依赖的库: requests #用来获取页面内容 BeautifulSoup #opython3不能安装BeautifulSoup,但可以安装Bea ...

随机推荐

  1. Dockerfile 中的 multi-stage(多阶段构建)

    在应用了容器技术的软件开发过程中,控制容器镜像的大小可是一件费时费力的事情.如果我们构建的镜像既是编译软件的环境,又是软件最终的运行环境,这是很难控制镜像大小的.所以常见的配置模式为:分别为软件的编译 ...

  2. 使用Python开发chrome插件

    本文由 伯乐在线 - xianhu 翻译,Daetalus 校稿.未经许可,禁止转载!英文出处:pythonspot.com.欢迎加入翻译小组. 谷歌Chrome插件是使用HTML.JavaScrip ...

  3. JavaScript基础回顾一(类型、值和变量)

    请看代码并思考输出结果 var scope = 'global'; function f(){ console.log(scope); var scope = 'local'; console.log ...

  4. GVRP 的工作机制和工作模式

    GVRP 简介 GVRP 基于 GARP 的工作机制来维护设备中的 VLAN 动态注册信息,并将该信息向其他设备传播:当设备启动了 GVRP 之后,就能够接收来自其他设备的 VLAN 注册信息,并动态 ...

  5. (void) (&_x == &_y)的作用

    如果有下面这段代码: #define min(x, y) ({ \ const typeof(x) _x = (x); \ const typeof(y) _y = (y); \ (void) (&a ...

  6. 关于 Cortex-M3 的双堆栈机制

    CM3 的堆栈分为两个:主堆栈和进程堆栈. 那么,这两个栈分别在什么情况下使用呢? 我们看一下CM3的控制寄存器(CONTROL):控制寄存器用于定义特权级别,还用于选择当前使用哪个堆栈指针. CON ...

  7. 分布式系统监视zabbix讲解七之分布式监控--技术流ken

    分布式监控 概述 Zabbix通过Zabbix proxy为IT基础设施提供有效和可用的分布式监控 代理(proxy)可用于代替Zabbix server本地收集数据,然后将数据报告给服务器. Pro ...

  8. linux安装配置zookeeper-3.4.10

    此文是基于上一篇文章:hadoop集群搭建 安装zookeeper: [在各个slave节点安装zookeeper] 下载地址:http://mirror.bit.edu.cn/apache/zook ...

  9. npm install -g @angular/cli@latest 失败

    一开始的ERROR信息是 error "@angular/compiler-cli" package was not properly installed 尝试方案二时又出现了以下 ...

  10. 如何把ASP.NET MVC项目部署到本地IIS上

    默认情况下,在VisualStudio中开发网站,会运行在IISExpress中,如果想把网站部署到本地的IIS服务器上该怎么办呢? 一.首先,以管理员身份运行VisualStudio,否则在修改项目 ...