python初学-爬取网页数据

python初学-爬取网页数据

1,获取网页源代码

import urllib
url = 'http://www.163.com'

wp = urllib.urlopen(url)
file_content = wp.read()

print file_content

2,将网页内容存入文件中

fp = open('163.txt', 'wb') #打开一个文本文件

fp.write(file_content) #写入数据

fp.close() #关闭文件

3,利用正则表达式快速的打印出网页的标题跟链接地址

import re
fp = open('163.txt', 'rb')
content = fp.read()
fp.close()

title = re.search('<title>(.*?)</title>', content, re.S).group(1)

print 'title = ', title + '\n'

hrefPatten = 'href="(.*?)"'

hrefC = re.findall(hrefPatten, content, re.S)  #返回所有匹配正则表达式的值于列表中

print 'Allhref = ', hrefC

for h in hrefC :
    print h

只是示例代码,演示爬取简单内容的简单过程,程序不完善,谢谢阅读,有不明白的可以回复讨论。

猜你喜欢

转载自blog.csdn.net/guo_hongjun1611/article/details/50440227