使用正则表达式抓取数据时遇到的小问题

前端之家收集整理的这篇文章主要介绍了使用正则表达式抓取数据时遇到的小问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_502_0@ @H_301_3@
@H_502_0@

本次目标时用正则表达式抓取一个网站的歌曲排行榜

部分源代码如下:

 1 <li>
 2 <input type="checkBox" value="[email protected]" name="Url" class="check">
 3 <span class="songNum ">38.</span>
 4 <a target="_1" href="/play/69933.htm" class="songName ">美丽的神话 《神话》电影主题</a>
 5 </li>
 6 <li>
 7 <input type="checkBox" value="[email protected]" name="Url" class="check">
 8 <span class="songNum ">39.</span>
 9 <a target="_1" href="/play/42474.htm" class="songName ">过火 </a>
10 </li>
11 <li>
12 <input type="checkBox" value="[email protected]" name="Url" class="check">
13 #<span class="songNum ">40.</span>
14 <a target="_1" href="/play/49771.htm" class="songName ">一生爱你千百回 </a>
15 </li>

可以看到,每一个<li>标签里存着一首歌的信息,包括,排名,地址,歌名。

按道理来说,写个正则匹配直接findall全出来了,但这个网站设了几点难点给我。

第一:

 1 <li>
 2 <input type="checkBox" value="[email protected]" name="Url" class="check">
 3 <span class="songNum topRed">01.</span>
 4 <a target="_1" href="/play/11417.htm" class="songName cBlue">大海 </a>
 5 </li>
 6 <li>
 7 <input type="checkBox" value="[email protected]" name="Url" class="check">
 8 <span class="songNum topRed">02.</span>
 9 <a target="_1" href="/play/64541.htm" class="songName ">天路 </a>
10 </li>
11 <li>
12 <input type="checkBox" value="[email protected]" name="Url" class="check">
13 <span class="songNum topRed">03.</span>
14 <a target="_1" href="/play/65937.htm" class="songName ">再回首 </a>
15 </li>

第一、二、三名的歌曲在songNum后面加了 topRed,还有在第一名的songName后面加了个cBlue。

解决方法

在写正则表达式时在相应的地方加上:(topRed)?  和(cBlue)?  ,()表示把字符归为一组,?表示匹配0个或者1个,也就是说,有的或者没有的都能匹配到,并且存储在组里。

 

第二:在每个排名的后面加了一个点。比如03.

解决方法

利用转义符   \

 

以后遇到类似的排名网站可以,比如op.gg,就能用这个方法解决了。

代码

results = re.findall(<li>.*?songNum (topRed)?">(.*?)\..*?href="(.*?)".*?songName (cBlue)?">(.*?)</a>,string,re.S)
for result in results:
    print(result[1],result[2],result[4])

 

遇到第二种解决方法了:

results = re.sub(topRed,‘‘,string)
results1 = re.sub(cBlue,results)
results2 = re.findall(<li>.*?songNum ">(.*?)\..*?href="(.*?)".*?songName ">(.*?)</a>,results1,re.S)
for result in results2:
    print(result[0],result[1],result[2])

用sub函数把topRed和cBlue给替换成空字符串

然后再按照原来写的正则表达式来抓取

@H_502_0@ @H_301_3@

猜你在找的正则表达式相关文章