国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python re正則匹配網頁中圖片url地址的方法

2020-02-16 00:14:32
字體:
來源:轉載
供稿:網友

最近寫了個python抓取必應搜索首頁http://cn.bing.com/的背景圖片并將此圖片更換為我的電腦桌面的程序,在正則匹配圖片url時遇到了匹配失敗問題。

要抓取的圖片地址如圖所示:

python re正則匹配網頁中圖片url地址

首先,使用這個pattern

reg = re.compile('.*g_img={url: "(http.*?jpg)"')

無論怎么匹配都匹配不到,后來把網頁源碼抓下來放在notepad++中查看,并用notepad++的正則匹配查找,很輕易就匹配到了,如圖:

python re正則匹配網頁中圖片url地址

后來我寫了個測試代碼,把圖片地址在的那一行保存在一個字符串中,很快就匹配到了,如下面代碼所示,data是匹配不到的,然而line是可以匹配到的。

# -*-coding:utf-8-*-import osimport re f = open('bing.html','r') line = r'''Bnp.Internal.Close(0,0,60056); } });;g_img={url: "https://az12410.vo.msecnd.net/homepage/app/2016hw/BingHalloween_BkgImg.jpg",id:'bgDiv',d:'200',cN'''data = f.read().decode('utf-8','ignore').encode('gbk','ignore') print " " reg = re.compile('.*g_img={url: "(http.*?jpg)"') if re.match(reg, data):  m1 = reg.findall(data)  print m1[0]else:  print("data Not match .")  print 20*'-'#print lineif re.match(reg, line):  m2 = reg.findall(line)  print m2[0]else:  print("line Not match .")

由此可見line和data是有區別的,什么區別呢?那就是data是多行的,包含換行符,而line是單行的,沒有換行符。我有在字符串line中加了換行符,結果line沒有匹配到。

到這了原因就清楚了。原因就在這句話

re.compile('.*g_img={url: "(http.*?jpg)"')。

后來翻閱python文檔,發現re.compile()這個函數的第二個可選參數flags。這個參數是re中定義的常量,有如下常量

re.DEBUG Display debug information about compiled expression.re.I re.IGNORECASE Perform case-insensitive matching; expressions like [A-Z] will match lowercase letters, too. This is not affected by the current locale.
re.L re.LOCALE Make /w, /W, /b, /B, /s and /S dependent on the current locale.
re.M re.MULTILINE When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character '$' matches at the end of the string and at the end of each line (immediately preceding each newline). By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline (if any) at the end of the string.
re.S re.DOTALL Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.re.U re.UNICODE Make /w, /W, /b, /B, /d, /D, /s and /S dependent on the Unicode character properties database.New in version 2.0.            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 通山县| 镇坪县| 云安县| 四川省| 顺平县| 秭归县| 红桥区| 德州市| 平凉市| 鸡西市| 莱西市| 商水县| 澳门| 柳州市| 仙桃市| 武城县| 赤城县| 正定县| 湟中县| 九江县| 蒲城县| 萍乡市| 山阴县| 青州市| 丰都县| 伊宁县| 保定市| 濉溪县| 城口县| 信丰县| 郑州市| 金湖县| 秦皇岛市| 阳高县| 阆中市| 开鲁县| 容城县| 花莲市| 鄂托克前旗| 金川县| 衡阳县|