python七大爬虫程序

news/2024/7/19 11:21:09 标签: python, 爬虫, 开发语言

一,爬取豆瓣电影信息

python">import random
import urllib.request
from bs4 import BeautifulSoup
import codecs
from time import sleep

def main(url, headers):
    # 发送请求
    page = urllib.request.Request(url, headers=headers)
    page = urllib.request.urlopen(page)
    contents = page.read()
    # 用BeautifulSoup解析网页
    soup = BeautifulSoup(contents, "html.parser")
    infofile.write("")
    print('爬取豆瓣电影250: \n')

    for tag in soup.find_all(attrs={"class": "item"}):
        # 爬取序号
        num = tag.find('em').get_text()
        print(num)
        infofile.write(num + "\r\n")
        # 电影名称
        name = tag.find_all(attrs={"class": "title"})
        zwname = name[0].get_text()
        print('[中文名称]', zwname)
        infofile.write("[中文名称]" + zwname + "\r\n")
        # 网页链接
        url_movie = tag.find(attrs={"class": "hd"}).a
        urls = url_movie.attrs['href']
        print('[网页链接]', urls)
        infofile.write("[网页链接]" + urls + "\r\n")
        # 爬取评分和评论数
        info = tag.find(attrs={"class": "star"}).get_text()
        info = info.replace('\n', ' ')
        info = info.lstrip()
        print('[评分评论]', info)
        # 获取评语
        info = tag.find(attrs={"class": "inq"})
        if (info):  # 避免没有影评调用get_text()报错
            content = info.get_text()
            print('[影评]', content)
            infofile.write(u"[影评]" + content + "\r\n")
        print('')


if __name__ == '__main__':
    # 存储文件
    infofile = codecs.open("豆瓣电影信息.txt", 'a', 'utf-8')
    # 消息头
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'}
    # 翻页
    i = 0
    while i < 10:
        print('页码', (i + 1))
        num = i * 25  # 每次显示25部 URL序号按25增加
        url = 'https://movie.douban.com/top250?start=' + str(num) + '&filter='
        main(url, headers)
        sleep(5 + random.random())
        infofile.write("\r\n\r\n")
        i = i + 1
    infofile.close()

二,爬取知乎网页内容

python">import csv
import requests
import re
import time

def main(page):
    url = f'https://tieba.baidu.com/p/7882177660?pn={page}'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'
    }
    resp = requests.get(url,headers=headers)
    html = resp.text
    # 评论内容
    comments = re.findall('style="display:;">                    (.*?)</div>',html)
    # 评论用户
    users = re.findall('class="p_author_name j_user_card" href=".*?" target="_blank">(.*?)</a>',html)
    # 评论时间
    comment_times = re.findall('楼</span><span class="tail-info">(.*?)</span><div',html)
    for u,c,t in zip(users,comments,comment_times):
        # 筛选数据,过滤掉异常数据
        if 'img' in c or 'div' in c or len(u)>50:
            continue
        csvwriter.writerow((u,t,c))
        print(u,t,c)
    print(f'第{page}页爬取完毕')

if __name__ == '__main__':
    with open('01.csv','a',encoding='utf-8')as f:
        csvwriter = csv.writer(f)
        csvwriter.writerow(('评论用户','评论时间','评论内容'))
        for page in range(1,8):  # 爬取前7页的内容
            main(page)
            time.sleep(2)

三,爬起天气预报

import requests
from bs4 import BeautifulSoup
import urllib.request
import random
# 设置header 防止产生403forbidden
my_headers = [
    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36",
    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14",
    "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)",
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
    'Opera/9.25 (Windows NT 5.1; U; en)',
    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
    'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
    'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
    "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7",
    "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 "
]
# 抓取网页信息
def get_content(url, headers):
    random_header = random.choice(headers)
    req = urllib.request.Request(url)
    req.add_header("User-Agent", random_header)
    req.add_header("Host", "lishi.tianqi.com")
    req.add_header("Referer", "http://lishi.tianqi.com/")
    req.add_header("GET", url)
 
    content = urllib.request.urlopen(req).read()
    return content
    # 三个月份天气的链接
urls = ["http://lishi.tianqi.com/wuhan/202210.html",
        "http://lishi.tianqi.com/wuhan/202211.html",
        "http://lishi.tianqi.com/wuhan/202212.html"]
 
file = open('weather.csv', 'w')
for url in urls:
    response = get_content(url, my_headers)
    soup = BeautifulSoup(response, 'html.parser')
    weather_list = soup.select('ul[class="thrui"]')
 
    for weather in weather_list:
        ul_list = weather.select('li')
        for ul in ul_list:
            li_list = ul.select('div')
            str = ""
            for li in li_list:
                str += li.string + ','
            file.write(str + '\n')
file.close()

四,爬取网页标题

import requests
from bs4 import BeautifulSoup
url = "http://project.webcat.top/bx/80607/24411"
# 发送请求
response = requests.get(url)
# 使用BeautifulSoup解析HTML内容
soup = BeautifulSoup(response.content,'html.parser')
# 获取网站标题
title = soup.title.string
print("网站标题:", title)

五,爬取网页所有链接

python">import requests
from bs4 import BeautifulSoup

# 发送HTTP请求获取网页内容
url = 'https://www.python.org/'
response = requests.get(url)
html_content = response.text

# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(html_content, 'html.parser')

# 提取需要的数据
# 这里以提取网页中的所有链接为例
links = soup.find_all('a')
for link in links:
    print(link.get('href'))

六,爬取网页图片

python">import requests
from bs4 import BeautifulSoup
import urllib

# 爬取网页数据并解析数据
url = 'http://vip.1905.com/m/play/1655899.shtml'  # 替换为你要爬取的网页地址
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 解析数据并获取影视图片的URL
image_urls = []
images = soup.find_all('img')
for image in images:
    image_url = image['src']
    image_urls.append(image_url)

# 下载图片并保存到本地文件
for image_url in image_urls:
    urllib.request.urlretrieve(image_url, 'rrr.jpg')  # 替换为你要保存的文件名和路径

七,爬取网页完整文本

python">import requests
from bs4 import BeautifulSoup

def scrape_html(url):
    # 发送HTTP请求
    response = requests.get(url)
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        # 找到并打印所有的段落标签(<p>)的内容
        for p_tag in soup.find_all('p'):
            print(p_tag.get_text())
    else:
        print(f"Error: {response.status_code} when fetching {url}")

# 测试函数
scrape_html('https://www.bafangwy.com/')  # 替换为你要爬取的网址

http://www.niftyadmin.cn/n/5404451.html

相关文章

【Vue3】全局切换字体大小

VueUse 先安装VueUse <template><header><div class"left">left</div><div class"center">center</div><div class"right">right</div></header><div><button click"cha…

STL-内存的配置与释放

STL-内存的配置与释放 STL有两级空间配置器&#xff0c;默认是使用第二级。第二级空间配置器会在某些情况下去调用第一级空间配置器。空间配置器都是在allocate函数内分配内存&#xff0c;在deallocate函数内释放内存。 第一级空间配置器 第一级配置器只是对malloc函数和fre…

考研复试类比社团招新,无所谓“公平”,导师选谁都是他的权力

这篇文章是抖音和b站上上传的同名视频的原文稿件&#xff0c;感兴趣的csdn用户可以关注我的抖音和b站账号&#xff08;GeekPower极客力量&#xff09;。同时这篇文章也为视频观众提供方便&#xff0c;可以更加冷静地分析和思考。文章同时在知乎发表。 我考研一战的时候计算机考…

SpringBoot的基本了解

SpringBoot能广泛应用的原因 1:独立运行 Spring Boot而且内嵌了各种servlet容器,Tomcat、Jetty等,现在不再需要打成war包部署到容器 中,Spring Boot只要打成一个可执行的jar包就能独立运行,所有的依赖包都在一个jar包内。 2:简化配置 spring-boot-starter-web启动器自动…

【2024-03-02】京东春招笔试两道编程题解

恭喜发现宝藏!搜索公众号【TechGuide】回复公司名,解锁更多新鲜好文和互联网大厂的笔经面经。 作者@TechGuide【全网同名】 订阅专栏: 【专享版】2024最新大厂笔试真题解析,错过必后悔的宝藏资源! 第一题:字符串查找 题目描述 小盖是一个善于寻找快乐的人。对于一个字…

先进电气技术 —— 母线电容器的老化预测

在电气工程领域&#xff0c;老化问题是一个常见的问题&#xff0c;诸如电机老化、线路老化、功率开关管老化、直流母线电容器老化以及电池老化等等&#xff0c;因此“对系统器件的寿命预测”成为了工业界和学术界的一个研究热点问题。 一、背景 电容器广泛应用于电力电子变换器…

Java自学day4

算术运算符 数字相加 数字进行运算时,数据类型不一样不能运算,需要转成一样的,才能运算。 类型转换的分类: 1.隐式转换(自动类型提升):取值范围小的数值转向取值范围大的数值 隐式转换小结: 取值范围:byte<short<int<long<float<double数据…

【深度学习笔记】计算机视觉——锚框

锚框 目标检测算法通常会在输入图像中采样大量的区域&#xff0c;然后判断这些区域中是否包含我们感兴趣的目标&#xff0c;并调整区域边界从而更准确地预测目标的真实边界框&#xff08;ground-truth bounding box&#xff09;。 不同的模型使用的区域采样方法可能不同。 这里…