urllib 爬虫示例

爬虫爬取糗事百科的段子

#coding=utf8
import urllib.request
import re
import os

#爬取糗事百科。
#定义爬取第几页
page = 1  

#http请求的一个参数,如果没有网站服务器可能不会允许你访问
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'

#要爬取的url地址
url = 'http://www.qiushibaike.com/hot/page/' + str(page)

#这是http请求header头字典
headers = { 'User-Agent' : user_agent }

#发送http请求返回response对象
request = urllib.request.Request(url,headers=headers)
response = urllib.request.urlopen(request)

#获取返回的html内容并进行utf-8编码(这个html页面是最原始的页面不是ajax异步请求后的页面)
html = response.read().decode('utf8')

#匹配正则表达式。这里的问号是关键非贪婪模式
pattern = re.compile('[\s\S]*?\n*(.*?)\n*\n*')
#array = re.findiall(pattern,html)
#此函数返回string中所有与pattern相匹配的全部字串,返回形式为迭代器。
array = re.finditer(pattern,html)

#写入文件
file = open("糗事百科.txt","a")
for a in array:
    #print(a.groups())#区别一下group与groups
    #print(a.group(1))#不传参默认返回源字符串。
    
    #在正则表达式中一个小括号围起来的算一个分组
    file.write(a.group(1))
    file.write('\n\n')
print("写入完毕")

 

 

抓取百度贴吧内容

url = input("请输入要抓取的贴吧地址:")

#请求url获得html内容
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
html = response.read().decode('utf8')
print(html)

#获取贴吧的话题。
pattern = re.compile('<h3\s*class="core_title_txt.*?>(.*?)</h3>')
result = re.search(pattern,html)#只搜索一次搜到即结束
print("贴吧话题:  ")
print(result.group(1))
print("--------------------------------------------------------\n")

#获取内容
#下面的最后一个问号很关键。
pattern = re.compile('<div[\s\S]*?class="d_post_content j_d_post_content "\s*>([\s\S]*?)
(<img[\s\S]*?|<a[\s\S]*?)?</div>'+
'[\s\S]*?(<ul\s*class="j_lzl_m_w"[\s\S]*?>([\s\S]*?)</ul>)?' )

result = re.finditer(pattern,html)
floor = 1
for a in result:
    print(floor,"楼:")
    print(a.group(1))
    print("---------------------------------------------------------\n")
    floor=floor+1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值