python爬虫例子如何在官网上找相关的例子?

& & & & python 打开浏览器,可以做简单的刷网页的小程序。仅供学习,别用非法用途。& & python的webbrowser模块支持对浏览器进行一些操作,主要有以下三个方法:& & 复制代码代码如下:& & webbrowser.open(url,……
声明:该文章系网友上传分享,此内容仅代表网友个人经验或观点,不代表本网站立场和观点;若未进行原创声明,则表明该文章系转载自互联网;若该文章内容涉嫌侵权,请及时向
论文写作技巧
上一篇:下一篇:
相关经验教程python网络编程之读取网站根目录实例_python_ThinkSAAS
python网络编程之读取网站根目录实例
python网络编程之读取网站根目录实例
内容来源: 网络
本文实例讲述了python网络编程之读取网站根目录的方法,分享给大家供大家参考。
具体实现方法如下:
import socket, sys 
port = 70 
host = "quux.org" 
filename = "//" 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((host, port)) 
s.sendall(filename+"rn") 
while(1): 
buf = s.recv(2048) 
if not buf: 
break 
sys.stdout.write(buf) 
本文实例运行环境为Python2.7.6
该实例会返回quux.org的根目录的列表
返回结果如下:
iWelcome to gopher at quux.org! fake (NULL) 0
i fake (NULL) 0
iThis server has a lot of information of historic interest, fake (NULL) 0
ifunny, or just plain entertaining -- all presented in Gopher. fake (NULL) 0
iThere are many mirrors here of rare or valuable files with the fake (NULL) 0
iaim to preserve them in case their host disappears. PLEASE READ fake (NULL) 0
i"About This Server" FOR IMPORTANT NOTES AND LEGAL INFORMATION. fake (NULL) 0
i fake (NULL) 0
0About This Server /About This Server.txt gopher.quux.org 70 +
1Archives /Archives gopher.quux.org 70 +
1Books /Books gopher.quux.org 70 +
1Communication /Communication gopher.quux.org 70 +
iThis directory contains the entire text of the book fake (NULL) 0
i"We the Media: Grassroots Journalism by the People, for the People" fake (NULL) 0
iby Dan Gillmor in various formats. fake (NULL) 0
i fake (NULL) 0
iFeel free to download and enjoy. fake (NULL) 0
1Computers /Computers gopher.quux.org 70 +
1Current Issues and Events (Updated Apr. 23, 2002) /Current gopher.quux.org 70 +
1Development Projects /devel gopher.quux.org 70 +
0Gopher&s 10th Anniversary /3.0.0.txt gopher.quux.org 70
1Government, Politics, Law, and Conflict /Government gopher.quux.org 70 +
0How To Help /How To Help.txt gopher.quux.org 70 +
1Humor and Fun /Humor and Fun gopher.quux.org 70 +
1Index to Quux.Org /Archives/index gopher.quux.org 70
1Internet /Internet gopher.quux.org 70 +
1Other Gopher Servers /Software/Gopher/servers gopher.quux.org 70
1People /People gopher.quux.org 70 +
1Reference /Reference gopher.quux.org 70 +
1Software and Downloads /Software gopher.quux.org 70 +
1The Gopher Project /Software/Gopher gopher.quux.org 70
0What&s New /whatsnew.txt gopher.quux.org 70 +
希望本文所述对大家的Python程序设计有所帮助
PHP开发框架
开发工具/编程工具
服务器环境
ThinkSAAS商业授权:
ThinkSAAS为用户提供有偿个性定制开发服务
ThinkSAAS将为商业授权用户提供二次开发指导和技术支持
让ThinkSAAS更好,把建议拿来。
开发客服微信27204人阅读
python(2)
最近两天学习了一下python,并自己写了一个网络爬虫的例子。
python版本: 3.5
IDE : pycharm 5.0.4
要用到的包可以用pycharm下载:
File-&Default Settings-&Default Project-&Project Interpreter
选择python版本并点右边的加号安装想要的包
我选择的网站是中国天气网中的苏州天气,准备抓取最近7天的天气以及最高/最低气温
程序开头我们添加:
这样就能告诉解释器该py程序是utf-8编码的,源程序中可以有中文。
要引用的包:
import requests
import csv
import random
import time
import socket
import http.client
from bs4 import BeautifulSoup
requests:用来抓取网页的html源代码
csv:将数据写入到csv文件中
random:取随机数
time:时间相关操作
socket和http.client 在这里只用于异常处理
BeautifulSoup:用来代替正则式取源码中相应标签中的内容
urllib.request:另一种抓取网页的html源代码的方法,但是没requests方便(我一开始用的是这一种)
获取网页中的html代码:
def get_content(url , data = None):
'Accept': 'text/html,application/xhtml+xml,application/q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'zh-CN,q=0.8',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
timeout = random.choice(range(80, 180))
while True:
rep = requests.get(url,headers = header,timeout = timeout)
rep.encoding = 'utf-8'
except socket.timeout as e:
print( '3:', e)
time.sleep(random.choice(range(8,15)))
except socket.error as e:
print( '4:', e)
time.sleep(random.choice(range(20, 60)))
except http.client.BadStatusLine as e:
print( '5:', e)
time.sleep(random.choice(range(30, 80)))
except http.client.IncompleteRead as e:
print( '6:', e)
time.sleep(random.choice(range(5, 15)))
return rep.text
header是requests.get的一个参数,目的是模拟浏览器访问
header 可以使用chrome的开发者工具获得,具体方法如下:
打开chrome,按F12,选择network
重新访问该网站,找到第一个网络请求,查看它的header
timeout是设定的一个超时时间,取随机数是因为防止被网站认定为网络爬虫。
然后通过requests.get方法获取网页的源代码、
rep.encoding = ‘utf-8’是将源代码的编码格式改为utf-8(不该源代码中中文部分会为乱码)
下面是一些异常处理
返回 rep.text
获取html中我们所需要的字段:
这里我们主要要用到BeautifulSoup
BeautifulSoup 文档
首先还是用开发者工具查看网页源码,并找到所需字段的相应位置
找到我们需要字段都在 id = “7d”的“div”的ul中。日期在每个li中h1 中,天气状况在每个li的第一个p标签内,最高温度和最低温度在每个li的span和i标签中。
感谢Joey_Ko指出的错误:到了傍晚,当天气温会没有最高温度,所以要多加一个判断。
代码如下:
def get_data(html_text):
final = []
bs = BeautifulSoup(html_text, "html.parser")
body = bs.body
data = body.find('div', {'id': '7d'})
ul = data.find('ul')
li = ul.find_all('li')
for day in li:
date = day.find('h1').string
temp.append(date)
inf = day.find_all('p')
temp.append(inf[0].string,)
if inf[1].find('span') is None:
temperature_highest = None
temperature_highest = inf[1].find('span').string
temperature_highest = temperature_highest.replace('℃', '')
temperature_lowest = inf[1].find('i').string
temperature_lowest = temperature_lowest.replace('℃', '')
temp.append(temperature_highest)
temp.append(temperature_lowest)
final.append(temp)
return final
写入文件csv:
将数据抓取出来后我们要将他们写入文件,具体代码如下:
def write_data(data, name):
file_name = name
with open(file_name, 'a', errors='ignore', newline='') as f:
f_csv = csv.writer(f)
f_csv.writerows(data)
if __name__ == '__main__':
url ='.cn/weather/.shtml'
html = get_content(url)
result = get_data(html)
write_data(result, 'weather.csv')
然后运行一下:
生成的weather.csv文件如下:
总结一下,从网页上抓取内容大致分3步:
1、模拟浏览器访问,获取html源代码
2、通过正则匹配,获取指定标签中的内容
3、将获取到的内容写到文件中
刚学python爬虫,可能有些理解有错误的地方,请大家批评指正,谢谢!
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:37871次
排名:千里之外
评论:27条
(5)(1)(1)(1)类和实例 - 廖雪峰的官方网站
面向对象最重要的概念就是类(Class)和实例(Instance),必须牢记类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。
仍以Student类为例,在Python中,定义类是通过class关键字:
class Student(object):
class后面紧接着是类名,即Student,类名通常是大写开头的单词,紧接着是(object),表示该类是从哪个类继承下来的,继承的概念我们后面再讲,通常,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类。
定义好了Student类,就可以根据Student类创建出Student的实例,创建实例是通过类名+()实现的:
&&& bart = Student()
&__main__.Student object at 0x10a67a590&
&&& Student
&class '__main__.Student'&
可以看到,变量bart指向的就是一个Student的object,后面的0x10a67a590是内存地址,每个object的地址都不一样,而Student本身则是一个类。
可以自由地给一个实例变量绑定属性,比如,给实例bart绑定一个name属性:
&&& bart.name = 'Bart Simpson'
&&& bart.name
'Bart Simpson'
由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。通过定义一个特殊的__init__方法,在创建实例的时候,就把name,score等属性绑上去:
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
注意到__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。
有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去:
&&& bart = Student('Bart Simpson', 59)
&&& bart.name
'Bart Simpson'
&&& bart.score
和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,并且,调用时,不用传递该参数。除此之外,类的方法和普通函数没有什么区别,所以,你仍然可以用默认参数、可变参数和关键字参数。
面向对象编程的一个重要特点就是数据封装。在上面的Student类中,每个实例就拥有各自的name和score这些数据。我们可以通过函数来访问这些数据,比如打印一个学生的成绩:
&&& def print_score(std):
print '%s: %s' % (std.name, std.score)
&&& print_score(bart)
Bart Simpson: 59
但是,既然Student实例本身就拥有这些数据,要访问这些数据,就没有必要从外面的函数去访问,可以直接在Student类的内部定义访问数据的函数,这样,就把“数据”给封装起来了。这些封装数据的函数是和Student类本身是关联起来的,我们称之为类的方法:
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print '%s: %s' % (self.name, self.score)
要定义一个方法,除了第一个参数是self外,其他和普通函数一样。要调用一个方法,只需要在实例变量上直接调用,除了self不用传递,其他参数正常传入:
&&& bart.print_score()
Bart Simpson: 59
这样一来,我们从外部看Student类,就只需要知道,创建实例需要给出name和score,而如何打印,都是在Student类的内部定义的,这些数据和逻辑被“封装”起来了,调用很容易,但却不用知道内部实现的细节。
封装的另一个好处是可以给Student类增加新的方法,比如get_grade:
class Student(object):
def get_grade(self):
if self.score &= 90:
return 'A'
elif self.score &= 60:
return 'B'
return 'C'
同样的,get_grade方法可以直接在实例变量上调用,不需要知道内部实现细节:
&&& bart.get_grade()
'C'
类是创建实例的模板,而实例则是一个一个具体的对象,各个实例拥有的数据都互相独立,互不影响;
方法就是与实例绑定的函数,和普通函数不同,方法可以直接访问实例的数据;
通过在实例上调用方法,我们就直接操作了对象内部的数据,但无需知道方法内部的实现细节。
和静态语言不同,Python允许对实例变量绑定任何数据,也就是说,对于两个实例变量,虽然它们都是同一个类的不同实例,但拥有的变量名称都可能不同:
&&& bart = Student('Bart Simpson', 59)
&&& lisa = Student('Lisa Simpson', 87)
&&& bart.age = 8
&&& bart.age
&&& lisa.age
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
AttributeError: 'Student' object has no attribute 'age'
Make a Comment
Sign In to Make a Comment
You can sign in directly without register:
You need authorize to allow connect to your social passport for the first time.
WARNING: You are using an old browser that does not support HTML5.
Please choose a modern browser ( /
/ ) to get a good experience.

我要回帖

更多关于 python正则表达式例子 的文章

 

随机推荐