目标:
python脚本爬取今日百度热点新闻
知识点:
- python3使用 urllib.request.urlopen 去打开一个特定网址
- 中文可以加 decode(‘gbk’) 来避免乱码
- re.S 用来解决跨行匹配的问题,用法: re.compile(pattern, re.S)
代码
import urllib.request
import re
url = 'http://news.baidu.com/'
content = urllib.request.urlopen(url).read().decode('gbk')
#Example:
#<li class="hdline0">
#<i class="dot"></i>
#<strong>
#<a href="http://china.huanqiu.com/article/2016-07/9209287.html?from=bdwz " target="_blank" class="a3" mon="ct=1&a=1&c=top&pn=0">xxx:扶贫工作不搞层层加码</a>
#</strong>
#</li>
pattern = re.compile('<li class="hd.*?<strong>.*?<a.*?>(.*?)</a>.*?strong>', re.S)
hotNews = re.findall(pattern, content)
for i in hotNews:
print(i)