python爬虫

print("你好,世界")

# pip install openpyxl 安装插件

import requests #requests是HTTP库

import re

from openpyxl import workbook # 写入Excel表所用

from openpyxl import load_workbook # 读取Excel表所用

from bs4 import BeautifulSoup as bs #bs:通过解析文档为用户提供需要抓取的数据

import os

import io

import sys

sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码

#我们开始利用requests.get()来获取网页并利用bs4解析网页:

def getData(src):

html = requests.get(src).content # requests.get(src)返回的是状态码<Response [200]>,加上.content以字节形式(二进制返回数据。 和前端一样,分为get post等 http://www.cnblogs.com/ranxf/p/7808537.html

soup = bs(html,'html.parser') # lxml解析器解析字节形式的数据,得到完整的类似页面的html代码结构的数据

print(soup)

global ws

Name = []

Introductions = []

introductions = soup.find_all("a",class_="book-item-name")

nameList = soup.find_all("a",class_="author")

print (nameList)

for name in nameList:

print (name.text)

Name.append(name.text)

for introduction in introductions:

Introductions.append(introduction.text)

for i in range(len(Name)):

ws.append([Name[i],Introductions[i]])

if __name__ == '__main__':

# 读取存在的Excel表测试

# wb = load_workbook('t est.xlsx') #加载存在的Excel表

# a_sheet = wb.get_sheet_by_name('Sheet1') #根据表名获取表对象

# for row in a_sheet.rows: #遍历输出行数据

# for cell in row: #每行的 每一个单元格

# print cell.value,

# 创建Excel表并写入数据

wb = workbook.Workbook() # 创建Excel对象

ws = wb.active # 获取当前正在操作的表对象

# 往表中写入标题行,以列表形式写入!

ws.append(['角色名字', '票数'])

src = 'http://www.lrts.me/book/category/3058'

getData(src)

wb.save('qinshi.xlsx') # 存入所有信息后,保存为filename.xlsx

================================================================================================

# coding:utf-8

import urllib.request

import urllib.error

from bs4 import BeautifulSoup

import time

import random

# 使用LXML的方式来代替BeautifulSoup的方式

def download(url, user_agent='wswp', num_retries=2):

print('downloading: %', url)

# 防止对方禁用Python的代理,导致forbidden错误

headers = {'User-agent': user_agent}

request = urllib.request.Request(url, headers=headers)

try:

html = urllib.request.urlopen(request).read()

except urllib.error.URLError as e:

print('download error:', e.reason)

html = None

if num_retries > 0:

# URLError是一个上层的类,因此HttpERROR是可以被捕获到的。code是HttpError里面的一个字段

if hasattr(e, 'code') and 500 <= e.code < 600:

return download(url, num_retries - 1)

return html

page_url = 'https://www.szyangxiao.com/txt197165.shtml'

html_result = download(page_url)

if html_result is None:

exit(1)

else:

pass

# 分析得到的结果,从中找到需要访问的内容

soup = BeautifulSoup(html_result, 'html.parser')

fixed_html = soup.prettify()

uls = soup.find_all('ul', attrs={'class': 'clearfix'})

lis = uls[1].find_all('li', attrs={'class': 'min-width'})

# 修改文件写入方式为byte方式。

with open(r'D:\study\红楼之庶子风流.txt', 'wb') as target_file_writer:

default_encode = 'utf-8'

new_line = '\n'.encode(default_encode)

for li in lis[340:]:

a = li.find('a')

href = a.get('href').replace('//', 'https://')

# 把字符串转换成byte,然后写入到文件中

text = a.text.replace('下载《红楼之庶子风流 ', '').replace('》txt', '').encode(default_encode)

target_file_writer.write(text)

target_file_writer.write(new_line)

# 把字符串转换成byte,然后写入到文件中。因为源文件为gbk的编码方式,因此需要先decode,然后重新encode

target_file_writer.write(download(href).decode('gbk').encode(default_encode))

target_file_writer.write(new_line)

time.sleep(random.randint(5, 10))

以上信息来源网络或书籍,只供学习,如存在侵权问题,请联系作者进行删除

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HELLO XF

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值