python 抓取网页代码

本文介绍了一个使用Python编写的简单爬虫程序,该程序能够从指定网页抓取Java代码并保存到本地。文章总结了在开发过程中遇到的问题及解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import re,urllib,urllib2,socket
import os
import random
import socket
import urllib2
import cookielib

ERROR = {
        '0':'Can not open the url,checck you net',
        '1':'Creat download dir error',
        '2':'The image links is empty',
        '3':'Download faild',
        '4':'Build soup error,the html is empty',
        '5':'Can not save the image to your disk',
    }

FILENAME = 0


class BrowserBase(object): 

    def __init__(self):
        socket.setdefaulttimeout(20)

    def speak(self,name,content):
        print '[%s]%s' %(name,content)

    def openurl(self,url):
        """
        打开网页
        """
        cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
        self.opener = urllib2.build_opener(cookie_support,urllib2.HTTPHandler)
        urllib2.install_opener(self.opener)
        user_agents = [
                    'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
                    'Opera/9.25 (Windows NT 5.1; U; en)',
                    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
                    'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
                    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
                    'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
                    "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7",
                    "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 ",

                    ] 
       
        agent = random.choice(user_agents)
        self.opener.addheaders = [("User-agent",agent),("Accept","*/*"),('Referer','http://www.google.com')]
        try:
            res = self.opener.open(url)
            urlSource= res.read()
            print urlSource
            
            pattern = re.compile(r'package.*?<',re.M | re.S)
            match = pattern.findall(urlSource)
            
             
            length = len(match)
            for i in range(0,length):
                print "##############"
                print match[i]
                print len(match[i])
                global FILENAME
                f= open(savepath+`FILENAME`+".java",'wb')
                f.write(match[i][0:len(match[i])-1])
                f.close()
                FILENAME +=1
                
        except Exception,e:
            self.speak(str(e) + url,'content')
            raise Exception
        else:
            return res



def get_code(url):

    urlSource = urllib.urlopen(url).read()
    print urlSource
    

    #pattern = re.compile(r'package(?!<)',re.M)
    pattern = re.compile(r'package')

    match = pattern.findall(urlSource)
    
    #print 
            
    
if __name__=='__main__':
    splider=BrowserBase()
    i=0;
    savepath = 'e:\\picture\\'
    splider.openurl('http://blog.csdn.net/m13666368773/article/details/7691871') 



1 写作缘由:

看这个页面上额《java与设计模式》

http://blog.csdn.net/m13666368773/article/details/7691871

会把代码复制下来,在跑以下,看看结果。(他的代码很规范)但是会很麻烦。于是就想写一个脚本爬下来。

2

遇到的问题总结:

2.1

问题: 用抓图片那个脚本来抓。报403错误。

解决:http://www.yihaomen.com/article/python/210.htm

2.2

问题:写好了正则表达式以后。不知道findall返回的是什么。

解决:findall返回的是一个list,直接用match【i】来访问对应。

2.3

问题:list长度

解决:len(match)

2.4

问题:写流的时候,希望文件名每次+1

解决:python 全局变量。

CONSTANT = 0

def modifyGlobal():
	global CONSTANT
	print(CONSTANT)
	CONSTANT += 1

if __name__ == '__main__':
	modifyGlobal()
	print(CONSTANT)


开始是用 global CONSTANT +=1.汗。

2.5

问题: string indices must be integers, not tuple

解决:用tab上面那个字符

2.6

问题:正则后面多一个“<”

解决:在流写的时候,对字符串进行截取。match[i][0:len(match[i])-1]

 

总结完毕

 

使用 Python 自动获取网页代码是一种常见且高效的网络爬虫技术,能够快速抓取和处理大量网页数据。在实际操作中,`requests` 是一个非常流行且易于使用的第三方库,它简化了 HTTP 请求的发送和响应的处理。 ### 使用 `requests` 获取网页代码 最基础的方式是通过发送 GET 请求来获取目标网站的内容: ```python import requests # 发送GET请求并获取网页代码 url = 'https://www.baidu.com' response = requests.get(url) source_code = response.text # 获取文本内容(可能需要处理编码) ``` 如果出现乱码问题,通常是因为服务器返回的数据使用了特定的字符集,而 `requests` 默认采用 `ISO-8859-1` 编码进行解码[^2]。可以通过以下方法解决乱码问题: ```python # 查看当前编码方式 print(response.encoding) # 手动指定正确的编码方式,例如 UTF-8 response.encoding = 'utf-8' source_code = response.text ``` 此外,也可以直接访问二进制内容并通过其他方式解码: ```python binary_content = response.content # 获取原始字节流 decoded_content = binary_content.decode('utf-8') # 使用正确编码手动解码 ``` ### 将网页代码保存至本地文件 为了持久化存储获取到的网页内容,可以将结果写入本地文件系统: ```python with open('webpage_source.html', 'w', encoding='utf-8') as file: file.write(source_code) ``` 这段代码会创建或覆盖名为 `webpage_source.html` 的文件,并将经过正确解码后的网页代码写入其中。 ### 处理更复杂的场景 对于需要进一步解析 HTML 内容的情况,推荐结合使用 `BeautifulSoup` 库来进行结构化分析: ```python from bs4 import BeautifulSoup soup = BeautifulSoup(source_code, 'html.parser') # 示例:提取所有链接 for link in soup.find_all('a'): print(link.get('href')) ``` 这种方法可以帮助开发者从页面中提取特定信息,而不是仅仅获取整个文档。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值