Python编写网络爬虫–牛刀小试

Python编写网络爬虫–牛刀小试本文参考网上的资料,编写简单的Python编写网络爬虫,做了网页内容的抓取,分析出链接的url并抓取。

大家好,又见面了,我是你们的朋友全栈君。

   本文参考网上的资料,编写简单的Python编写网络爬虫,做了网页内容的抓取,分析出链接的url并抓取。

      1.环境准备

          安装python3,PyCharm开发环境

      2.牛刀小试:          

# encoding:UTF-8
import urllib.request         #引入urllib工具

url = "http://www.baidu.com" #Url地址
data = urllib.request.urlopen(url).read()  # 使用urllib工具获取url的页面内容
data = data.decode('UTF-8')       #将格式转换为UTF-8格式
print(data)                 # 打印获取的页面信息

      输出结果:

<html><head>        <meta http-equiv="content-type" content="text/html;charset=utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=Edge">	<meta content="always" name="referrer">    <meta name="theme-color" content="#2932e1">    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />    <link rel="search" type="application/opensearchdescription+xml" href="/content-search.xml" title="百度搜索" />     <link rel="icon" sizes="any" mask href="//www.baidu.com/img/baidu.svg">			<link rel="dns-prefetch" href="//s1.bdstatic.com"/>	<link rel="dns-prefetch" href="//t1.baidu.com"/>	<link rel="dns-prefetch" href="//t2.baidu.com"/>	<link rel="dns-prefetch" href="//t3.baidu.com"/>	<link rel="dns-prefetch" href="//t10.baidu.com"/>	<link rel="dns-prefetch" href="//t11.baidu.com"/>	<link rel="dns-prefetch" href="//t12.baidu.com"/>	<link rel="dns-prefetch" href="//b1.bdstatic.com"/>        <title>百度一下,你就知道</title>    <style id="css_index" index="index" type="text/css">html,body{height:100%}html{overflow-y:auto}body{font:12px arial;text-align:;background:#fff}body,p,form,ul,li{margin:0;padding:0;list-style:none}body,form,#fm{position:relative}td{text-align:left}img{border:0}a{color:#00c}  ........ ........ 由于内容过多,此处省略<script>if(navigator.cookieEnabled){	document.cookie="NOJS=;expires=Sat, 01 Jan 2000 00:00:00 GMT";}</script></body></html>

  

      上述结果与打开www.baidu.com,然后右键“查看源代码”获取得到的内容相同。

   3.抓取页面中的链接页面


      

import re
import urllib.request
import urllib

from collections import deque   #引入队列

queue = deque()        #定义队列,保存待处理的url
visited = set()        # 保存已抓取的url

url = 'http://www.csdn.net'  # 入口页面, 可以换成别的

queue.append(url)     # 添加到待处理的队列中
cnt = 0               # 已抓取数

while queue:
    url = queue.popleft()  # 获取队列队首元素
    visited.add(url)  # 添加到已经访问set中

    print('已经抓取: ' + str(cnt) + '   正在抓取 <---  ' + url)
    print('已经抓取的url:', visited)
    cnt += 1

    try:
        urlop = urllib.request.urlopen(url)      #抓取
    except:
        print('抓取: ' + url + '   异常 ')
        continue

    if 'html' not in urlop.getheader('Content-Type'):   # 判断是否是html的url
        continue

    # 避免程序异常中止, 用try...catch处理异常
    try:
        data = urlop.read().decode('utf-8')
    except:
        continue

    # 正则表达式提取页面中所有队列, 并判断是否已经访问过, 如果没有访问过,则加入待抓取队列
    linkre = re.compile('href="(.+?)"')
    for x in linkre.findall(data):
        if 'http' in x and x not in visited:
            queue.append(x)
            print('加入队列 --->  ' + x)


输出结果:


已经抓取: 0   正在抓取 <---  http://www.csdn.net已经抓取的url: {'http://www.csdn.net'}加入队列 --->  http://c.csdnimg.cn/www/css/csdn_common.css加入队列 --->  http://c.csdnimg.cn/public/favicon.ico加入队列 --->  https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn ...... 此处省略加入队列 --->  http://powerlinux.csdn 加入队列 --->  http://www.csdn.net/tag/jquery 加入队列 --->  http://www.csdn.net/company/icp.html加入队列 --->  http://www.csdn.net/company/pifu.html加入队列 --->  http://www.hd315.gov.cn/beian/view.asp?bianhao=010202001032100010加入队列 --->  http://c.csdnimg.cn/comm_ask/css/ask_float_block.css已经抓取: 1   正在抓取 <---  http://c.csdnimg.cn/www/css/csdn_common.css已经抓取的url: {'http://c.csdnimg.cn/www/css/csdn_common.css', 'http://www.csdn.net'}已经抓取: 2   正在抓取 <---  http://c.csdnimg.cn/public/favicon.ico已经抓取的url: {'http://c.csdnimg.cn/www/css/csdn_common.css', 'http://www.csdn.net', 'http://c.csdnimg.cn/public/favicon.ico'}已经抓取: 3   正在抓取 <---  https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn已经抓取的url: {'http://c.csdnimg.cn/www/css/csdn_common.css', 'https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn', 'http://www.csdn.net', 'http://c.csdnimg.cn/public/favicon.ico'}加入队列 --->  http://edu.csdn.net/yearPromotion/detail/3加入队列 --->  /account/fpwd?action=forgotpassword&service=http%3A%2F%2Fmy.csdn.net%2Fmy%2Fmycsdn加入队列 --->  https://api.weibo.com/oauth2/authorize?client_id=2601122390&response_type=code&redirect_uri=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Flogin%3Foauth_provider%3DSinaWeiboProvider加入队列 --->  https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=75fvsy4v01jw1s&redirect_uri=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Flogin%3Foauth_provider%3DLinkedInProvider&state=DCEEFWF45453sdffef424加入队列 --->  https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=cePqkUpKCBrcnQtARTNPxxQG&redirect_uri=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Flogin%3Foauth_provider%3DBaiduProvider加入队列 --->  https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=100270989&redirect_uri=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Flogin%3Foauth_provider%3DQQProvider&state=test加入队列 --->  https://github.com/login/oauth/authorize?client_id=4bceac0b4d39cf045157&redirect_uri=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Flogin%3Foauth_provider%3DGitHubProvider加入队列 --->  /account/mobileregister?action=mobileRegisterView&service=http%3A%2F%2Fmy.csdn.net%2Fmy%2Fmycsdn已经抓取: 4   正在抓取 <---  http://passport.csdn.net/account/mobileregister?action=mobileRegister已经抓取的url: {'http://c.csdnimg.cn/www/css/csdn_common.css', 'http://www.csdn.net', 'http://passport.csdn.net/account/mobileregister?action=mobileRegister', 'http://c.csdnimg.cn/public/favicon.ico', 'https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn'}加入队列 --->  https://csdnimg.cn/public/common/toolbar/css/index.css加入队列 --->  /account/register?action=registerView&service=http://www.csdn.net已经抓取: 5   正在抓取 <---  https://passport.csdn.net/help/faq已经抓取的url: {'http://c.csdnimg.cn/www/css/csdn_common.css', 'http://www.csdn.net', 'http://passport.csdn.net/account/mobileregister?action=mobileRegister', 'http://c.csdnimg.cn/public/favicon.ico', 'https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn', 'https://passport.csdn.net/help/faq'}加入队列 --->  https://passport.csdn.net/account/changepassword加入队列 --->  https://passport.csdn.net/account/forgotpassword加入队列 --->  https://passport.csdn.net/account/forgotpassword已经抓取: 6   正在抓取 <---  http://news.csdn.net已经抓取的url: {'http://c.csdnimg.cn/www/css/csdn_common.css', 'http://www.csdn.net', 'http://passport.csdn.net/account/mobileregister?action=mobileRegister', 'http://c.csdnimg.cn/public/favicon.ico', 'http://news.csdn.net', 'https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn', 'https://passport.csdn.net/help/faq'}加入队列 --->  http://c.csdnimg.cn/public/common/toolbar/css/index.css


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/149561.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • vs2010密钥

    vs2010密钥vs2010密钥YCFHQ-9DWCY-DKV88-T2TMH-G7BHP转载于:https://www.cnblogs.com/andy_tigger/archive/2010/09/27/1837082.html

    2022年6月6日
    96
  • java中main方法的作用

    java中main方法的作用main方法是我们学习Java语言学习的第一个方法,也是每个java使用者最熟悉的方法,每个Java应用程序都必须有且仅有一个main方法。在eclipse里可以使用输入main,在按住Alt+/的方式快速创建main方法。可以说main方法是最简单的方法,因为main方法几乎是固定不变得,除了String[]args可以写成Stringargs[],以及args的名称可以改变外,其它所有均不…

    2022年5月25日
    61
  • windows2008 安装mysql_windows server2008安装mysql数据库

    windows2008 安装mysql_windows server2008安装mysql数据库一、环境配置服务器数据库:mysql5.7.12操作系统:WindowsServer200864位java:1.8二、安装配置步骤1、解压从官网下载的mysql-5.7.12-winx64.zip到C:\pgis\db\Mysql\mysql-5.7.12-winx642、修改路径C:\pgis\db\Mysql\mysql-5.7.12-winx64下的配置文件my-default.ini…

    2022年7月27日
    27
  • iOS 处理pfx文件

    iOS 处理pfx文件先普及下基础知识,pfx是公钥加密技术12号标准(PublicKeyCryptographyStandards#12,PKCS#12)为存储和传输用户或服务器私钥、公钥和证书而指定的一个可移植的格式。它是一种二进制格式,这些文件也称为PFX文件。详见百科我的pfx文件是由写C++的同事提供,里面包含秘钥,使用的时候需要先读取里面的数据,然后对数据进行base64编码,最后获得字

    2022年6月1日
    39
  • 编译树莓派Linux内核[通俗易懂]

    编译树莓派Linux内核[通俗易懂]  RaspberryPi内核Linux代码存储在GitHub中,可以在github.com/raspberrypi/linux上查看。一、下载linux内核源码gitclone–depth=1https://github.com/raspberrypi/linux  上面的命令将下载当前的活动分支。省略–depth=1将下载整个存储库,包括所有分支的完整历史记录,但占用更多的存储空间。要下载不同的分支,可以使用以下–branch选项:gitclone–depth=1–b

    2022年7月23日
    6
  • 前端代码规范七大原则_织梦自定义表单源码

    前端代码规范七大原则_织梦自定义表单源码前言有时候我们发送手机验证码,会发现1分钟只能发送1次,这是做了频率限制,限制的时间次数,都由开发者自己决定频率认证源码分析defcheck_throttles(self,request):

    2022年7月29日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号