request+正则表达式爬去微博热搜榜

本文分享了使用Python进行网络爬虫的基本实践,包括如何利用requests库发送HTTP请求,使用正则表达式解析网页数据,以及将抓取到的数据保存到本地文件。通过一个具体的实例,演示了从微博热门话题榜抓取链接和名称的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      由于项目需要,最近在学习基于python语言的网络爬虫,将自己简单的学习做一个记录,故撰写了这篇博客。直接写代码吧,理论我也讲不明白。

import requests       #导入请求库
import re             #正则表达式的函数库
import json           #json库
from requests.exceptions import RequestException  #requests的异常处理

def get_one_page(url):                      #采用get请求获取页面信息
    try:
        respond = requests.get(url)
        if respond.status_code == 200:
            return respond.text
        return None
    except RequestException:
        return None
def parse_one_page(html):                   #解析获取得页面信息               
    pattern = re.compile('<tr.*?<a.*?href="(.*?)".*?_blank">(.*?)</a>',re.S)
    results = re.findall(pattern,html)
    for result in results:
        yield {
            'href': result[0],
            'name': result[1]

        }
    return results
def write_to_file(content):               #获取内容写入文本文件
    with open('results.txt','a',encoding='utf-8')as f:
        f.write(json.dumps(content,ensure_ascii = False)+'\n')
        f.close()

def main():                              #主函数
    url = 'https://s.weibo.com/top/summary?cate=topicband&sudaref=www.baidu.com&display=0&retcode=6102'
    html = get_one_page(url)
    results = parse_one_page(html)
    for result in results:
        write_to_file(result)
        print(result)
   # print(html)
   # print(results)

if __name__=='__main__':
    main()
在Python中,我们可以使用requests库来发送HTTP请求获取网页内容,然后利用正则表达式(re模块)解析网页数据。以下是基本步骤: 1. **安装所需库**: 首先确保已经安装了`requests`和`beautifulsoup4`(用于HTML解析),如果没有,可以使用pip安装: ``` pip install requests beautifulsoup4 re ``` 2. **发送GET请求**: 使用requests库的get()函数发起对笔趣阁网站的GET请求,例如: ```python import requests url = "https://www.biquge5200.com/" # 笔趣阁主页URL response = requests.get(url) ``` 3. **检查响应状态码**: 确保请求成功,通常状态码200表示成功: ```python if response.status_code == 200: print("请求成功") else: print(f"请求失败,状态码:{response.status_code}") ``` 4. **解析HTML内容**: 使用BeautifulSoup库解析HTML内容: ```python from bs4 import BeautifulSoup soup = BeautifulSoup(response.text, 'html.parser') ``` 5. **查找目标信息**: 使用正则表达式或BeautifulSoup的find_all(), select()等方法找到需要的数据,比如文章标题、链接等。这里以标题为例: ```python title_regex = r'<h3 class="title">(.*?)</h3>' titles = soup.find_all(re.compile(title_regex)) for title in titles: print(title.text) ``` 6. **提取更多信息(如正文)**: 如果有多个标签或更复杂的结构,可以用类似的方式找到包含正文的元素。 注意:在实际编写虫时,请遵守网站的robots.txt规则,并尊重版权,合理使用抓取数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值