python爬取数据

2020-10-14  本文已影响0人  ryanxun
嘿,今天的你过的还好吗,今天学习一下python如何爬取网页数据

用到了两个包 requests bs4

  pip install requests
  pip install bs4
  pip install lxml

如果lxml死活安装不了请参照这篇文章
https://www.zhihu.com/question/30047496

以上是下载包的代码可以直接用cmd使用

接下来就需要引包

import requests
from bs4 import BeautifulSoup

爬虫的运行流程:
模拟浏览器向服务器发送http请求 get() post() option() del(),服务器像爬虫去返回数据
代码思路 :
1.使用代码去打开我们的网站 服务器会向我们返回数据
2.请求成功拿到数据后 去做数据筛选
3.把筛选好的数据利用文件操作保存到本地

def getBook(url) :
    response =requests.get(url)
    response.encoding = "utf-8"
    print(response.text)

url = 'http://www.biquw.com/book/94/'
getBook(url)

我这里是使用方法形式获取 ,这样我们就打开了我们的网页,接下来筛选数据
筛选数据的步骤
1.提取所有的小说章节名称
2.提取所有小说章节的a标签中的值,对主域名做字符串拼接并且二次
3.在小说内容页面,提取内容

  soup = BeautifulSoup(response.text,'lxml')
    data_list = soup.find("ul")
    for book in data_list.find_all('a'):
        book_url = "http://www.biquw.com/book/94/" + book['href']
        book_data = requests.get(book_url)
        book_data.encoding = "utf-8"
        soup = BeautifulSoup(book_data.text,"lxml")
        data = soup.find('div',{'id':'htmlContent'})

这样筛选数据就完成了,我们需要给他下载到本地来
我这采用的是 with open

        with open(book.text + '.txt','w',encoding='utf-8')as f:
            f.write(data.text)

整个流程就完事了

最后把整个代码贴上去

import requests
from bs4 import BeautifulSoup
# 使用代码去打开我们的网站  服务器会向我们返回数据
def getBook(url) :
    response =requests.get(url)
    #转成utf-8格式
    response.encoding = "utf-8"

#需要两个参数  筛选哪个网页,html解析库 lxml
    soup = BeautifulSoup(response.text,'lxml')
    data_list = soup.find("ul")
    for book in data_list.find_all('a'):
        book_url = "http://www.biquw.com/book/94/" + book['href']
        book_data = requests.get(book_url)
        book_data.encoding = "utf-8"
        soup = BeautifulSoup(book_data.text,"lxml")
        data = soup.find('div',{'id':'htmlContent'})

        with open(book.text + '.txt','w',encoding='utf-8')as f:
            f.write(data.text)
url = 'http://www.biquw.com/book/94/'
getBook(url)





没更新动态或者频繁更新动态的时候都是在认真生活

上一篇下一篇

猜你喜欢

热点阅读