Pyton实现简单爬虫和正则表达式的利用

看视频教程写爬虫,贴一下我写的代码


#!/usr/bin/python
#coding utf-8

import re
import urllib

def gethtml(url):
	page = urllib.urlopen(url)
	html = page.read()
	return html

def getjpg(html):
	rule = r'src="(http://imgsr.bai.com/forum/.*?\.jpg)" pic_ext='
	jpgurl = re.findall(rule,html)
	return jpgurl

url = 'http://tieba.baidu.com/p/2738151262?see_lz=1'
html = gethtml(url)

print getjpg(html)

可是打印出来的是一个空的列表

$ python getjpg.py
[]

这个绝对是正则表达式的问题,于是我把换我的正则表达式

rule = r'src="(.*?\.jpg)" pic_ext='

可是,这样的得到的是好多,好乱,肯定还不对. 如图:




刚开始猜测是因为正则表达式会匹配最长的字符,可是用 *?或+? 时表示尽可少的重复.

看网页源代码,我觉得我里最后的答案又接近了一步.



那我接下来继续改进正则表达式.

rule = r'src="(http://imgsrc.+?\.jpg)" pic_ext='

这样就好了.接下来添加下载及重命名部分.

	x =0
	for download in jpgurl:
		urllib.urlretrieve(download,'%s.jpg' %x)
		x+=1

结果如下:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python中将中缀表达式转换为后缀表达式的一种常见方法是使用栈。 具体步骤如下: 1. 创建一个空栈和一个空列表。 2. 从左到右遍历中缀表达式的每个字符。 3. 如果当前字符是数字,将其添加到列表的末尾。 4. 如果当前字符是左括号,将其压入栈中。 5. 如果当前字符是右括号,则将栈中所有操作符弹出并添加到列表中,直到遇到左括号为止。然后将左括号弹出但不添加到列表中。 6. 如果当前字符是操作符,将其压入栈中。但在此之前,需要先将栈中所有优先级大于或等于该操作符的操作符弹出并添加到列表中。 7. 当表达式的所有字符都已遍历完毕时,将栈中所有操作符弹出并添加到列表中。 8. 最终列表中的元素就是后缀表达式。 以下是一个示例代码: ``` def infix_to_postfix(expression): precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} stack = [] postfix = [] for char in expression: if char.isdigit(): postfix.append(char) elif char == '(': stack.append(char) elif char == ')': while stack[-1] != '(': postfix.append(stack.pop()) stack.pop() else: while stack and stack[-1] != '(' and precedence[char] <= precedence.get(stack[-1], 0): postfix.append(stack.pop()) stack.append(char) while stack: postfix.append(stack.pop()) return postfix ``` 使用示例: ``` expression = '3+4*2/(1-5)^2' postfix = infix_to_postfix(expression) print(postfix) # ['3', '4', '2', '*', '1', '5', '-', '2', '^', '/', '+'] ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值