用python正则表达式爬取百度热搜httpstopbaiducomboardtab=realtime标题
以下是使用Python正则表达式爬取百度热搜标题的示例代码:
import re
import requests
url = "https://top.baidu.com/board?tab=realtime"
response = requests.get(url)
html = response.text
pattern = re.compile('<a href="/(.*?)">(.*?)</a>', re.S)
results = pattern.findall(html)
for result in results:
print(result[1])
运行以上代码,即可输出百度热搜榜的实时热点标题。其中,正则表达式<a href="/(.*?)">(.*?)</a>用于匹配HTML中的热搜标题,re.S标志用于指定.匹配任意字符,包括换行符。通过findall方法,可以获取所有匹配结果,并依次输出热搜标题。
原文地址: https://www.cveoy.top/t/topic/eZnY 著作权归作者所有。请勿转载和采集!