python3 requests + BeautifulSoup 爬取阳光网投诉贴详情实例代码
用到了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 爬取阳光网投诉贴详情实例代码的更多相关文章
- Python爬虫学习三------requests+BeautifulSoup爬取简单网页
第一次第一次用MarkDown来写博客,先试试效果吧! 昨天2018俄罗斯世界杯拉开了大幕,作为一个伪球迷,当然也得为世界杯做出一点贡献啦. 于是今天就编写了一个爬虫程序将腾讯新闻下世界杯专题的相关新 ...
- 使用requests+BeautifulSoup爬取龙族V小说
这几天想看龙族最新版本,但是搜索半天发现 没有网站提供 下载, 我又只想下载后离线阅读(写代码已经很费眼睛了).无奈只有自己 爬取了. 这里记录一下,以后想看时,直接运行脚本 下载小说. 这里是从 ...
- python 爬虫 requests+BeautifulSoup 爬取巨潮资讯公司概况代码实例
第一次写一个算是比较完整的爬虫,自我感觉极差啊,代码low,效率差,也没有保存到本地文件或者数据库,强行使用了一波多线程导致数据顺序发生了变化... 贴在这里,引以为戒吧. # -*- coding: ...
- requests+BeautifulSoup | 爬取电影天堂全站电影资源
import requests import urllib.request as ur from bs4 import BeautifulSoup import csv import threadin ...
- python 爬虫(一) requests+BeautifulSoup 爬取简单网页代码示例
以前搞偷偷摸摸的事,不对,是搞爬虫都是用urllib,不过真的是很麻烦,下面就使用requests + BeautifulSoup 爬爬简单的网页. 详细介绍都在代码中注释了,大家可以参阅. # -* ...
- requests+beautifulsoup爬取豆瓣图书
使用Xpath和BeautifulSoup来解析网页可以说真的很简便. import requests from bs4 import BeautifulSoup from random import ...
- [实战演练]python3使用requests模块爬取页面内容
本文摘要: 1.安装pip 2.安装requests模块 3.安装beautifulsoup4 4.requests模块浅析 + 发送请求 + 传递URL参数 + 响应内容 + 获取网页编码 + 获取 ...
- Python使用urllib,urllib3,requests库+beautifulsoup爬取网页
Python使用urllib/urllib3/requests库+beautifulsoup爬取网页 urllib urllib3 requests 笔者在爬取时遇到的问题 1.结果不全 2.'抓取失 ...
- python爬取当当网的书籍信息并保存到csv文件
python爬取当当网的书籍信息并保存到csv文件 依赖的库: requests #用来获取页面内容 BeautifulSoup #opython3不能安装BeautifulSoup,但可以安装Bea ...
随机推荐
- Go基础系列:构建go程序
hello world 从一个简单的程序开始解释,将下面的内容放进test.go文件中,路径随意: package main import ( "fmt" ) func main( ...
- mybatis-generator插件执行报错:Cannot resolve classpath entry
记录一个小问题 使用了mybatis-generator插件自动生成实体类,DAO,Mapper,在执行时报错.报错信息如下 Failed to execute goal org.mybatis.ge ...
- C# 反射Reflection Assembly
反射反射程序员的快乐 一:什么叫反射 反射:是.net framework提供的一个访问metadata的帮助类,可以获取信息并且使用 反射的优点:动态 反射的缺点:1:稍微麻烦 2:能避开编译器的 ...
- 【转载】 C#中全角转半角以及半角转全角
半角指的是一个字符占用一个标准字符的位置.全角指一个字符占用两个标准字符位置的状态.在C#中,我们可以通过程序的方法,将相应的半角字符串信息转换为全角类型,也可以实现全角转半角功能. 相应封装好的方法 ...
- iis访问网络路径映射问题(UNC share)
最近在做一个功能,涉及到nas网络磁盘文件的保存和访问,在服务器上将对应的路径映射为Z盘,结果在iis上部署网站直接访问该路径,报无法找到该路径的错误. 用的是.net core开发,在vs直接启动程 ...
- C#实现给图片加边框的方法
Bitmap bit= new Bitmap(@"" + Path);//给图片加边框 //Bitmap bit = new Bitmap(Screen.AllScreens[0] ...
- No application encryption key has been specified.
环境:php7.1.10laravel5.5出现: 解决:在根目录下执行: php artisan key:generate OK问题解决
- 【Java每日一题】20170208
20170207问题解析请点击今日问题下方的“[Java每日一题]20170208”查看(问题解析在公众号首发,公众号ID:weknow619) package Feb2017; public cla ...
- Android Lifecycle使用
引言 Lifecycle 是官方提供的架构组件之一,目前已经是稳定版本,Lifecycle 组件包括LifecycleOwner.LifecycleObserver.Lifecycle 组件是执行操作 ...
- Excel通用类工具(二)
前言 上一篇中写到了用反射来处理类中的不用的属性,但是Excel的列名还得手动输入,这样还是比较麻烦的,今天这篇就利用自定义注解来解决手动传入列名的问题:其实很简单的,只需要在上一篇的基础上加一个类就 ...