python用正则表达式爬取百度热搜标题
以下是一个简单的python程序,使用正则表达式从百度热搜页面中提取标题:
import re
import requests
url = 'https://www.baidu.com/s?tn=news&rtt=4&bsst=1&cl=2&wd=&medium=0'
response = requests.get(url)
content = response.text
pattern = re.compile('<a href=".*?" target="_blank" class="title_\\w+">(.*?)</a>')
titles = pattern.findall(content)
for title in titles:
print(title)
这个程序首先使用requests库获取百度热搜页面的HTML内容,然后使用正则表达式模式匹配所有标题的标签。匹配到的标题存储在一个列表中,最后遍历列表并打印所有标题。
原文地址: https://www.cveoy.top/t/topic/eZti 著作权归作者所有。请勿转载和采集!