当前位置: 首页 > news >正文

织梦摄影网站源码凯里seo排名优化

织梦摄影网站源码,凯里seo排名优化,wordpress大学攻击,河北常见网站建设价格使用 Python 爬取站长素材简历模板 简介 在本教程中,我们将学习如何使用 Python 来爬取站长素材网站上的简历模板。我们将使用requests和BeautifulSoup库来发送 HTTP 请求和解析 HTML 页面。本教程将分为两个部分:第一部分是使用BeautifulSoup的方法&am…

使用 Python 爬取站长素材简历模板


简介

在本教程中,我们将学习如何使用 Python 来爬取站长素材网站上的简历模板。我们将使用requestsBeautifulSoup库来发送 HTTP 请求和解析 HTML 页面。本教程将分为两个部分:第一部分是使用BeautifulSoup的方法,第二部分是使用lxml的方法,并比较两者的差异。

环境准备

首先,确保你已经安装了 Python。然后,安装以下库:

pip install requests beautifulsoup4 lxml

方法一:使用 BeautifulSoup

1.导入库

import requests
from bs4 import BeautifulSoup
import os

2.创建文件夹用于保存爬取的简历图片

if not os.path.exists("resume_templates_images"):os.makedirs("resume_templates_images")

3.爬取第一页

first_page_url = "https://sc.chinaz.com/jianli/free.html"
response = requests.get(first_page_url)
response.encoding = 'utf-8'if response.status_code == 200:soup = BeautifulSoup(response.text, 'html.parser')templates = soup.find_all('div', class_='box col3 ws_block')for template in templates:link = template.find('a', target='_blank')['href']img = template.find('img')['src']if img.startswith('//'):img = 'https:' + imgtitle = template.find('p').find('a').text.strip()img_response = requests.get(img)if img_response.status_code == 200:img_name = f"{title.replace(' ', '_')}.jpg"img_path = os.path.join("resume_templates_images", img_name)with open(img_path, 'wb') as f:f.write(img_response.content)else:print(f"下载图片 {img} 失败,状态码: {img_response.status_code}")

4.爬取第二页到第五页

在这里插入代base_url = "https://sc.chinaz.com/jianli/free_"
for page_num in range(2, 6):url = f"{base_url}{page_num}.html"response = requests.get(url)response.encoding = 'utf-8'if response.status_code == 200:soup = BeautifulSoup(response.text, 'html.parser')templates = soup.find_all('div', class_='box col3 ws_block')for template in templates:link = template.find('a', target='_blank')['href']img = template.find('img')['src']if img.startswith('//'):img = 'https:' + imgtitle = template.find('p').find('a').text.strip()img_response = requests.get(img)if img_response.status_code == 200:img_name = f"{title.replace(' ', '_')}.jpg"img_path = os.path.join("resume_templates_images", img_name)with open(img_path, 'wb') as f:f.write(img_response.content)else:print(f"下载图片 {img} 失败,状态码: {img_response.status_code}")
码片

方法二:使用 lxml

first_page_url = "https://sc.chinaz.com/jianli/free.html"
response = requests.get(first_page_url)
response.encoding = 'utf-8'if response.status_code == 200:tree = etree.HTML(response.text)templates = tree.xpath('//div[@class="box col3 ws_block"]')for template in templates:link = template.xpath('.//a[@target="_blank"]/@href')[0]img = template.xpath('.//img/@src')[0]if img.startswith('//'):img = 'https:' + imgtitle = template.xpath('.//p/a[@class="title_wl"]/text()')[0].strip()img_response = requests.get(img)if img_response.status_code == 200:img_name = f"{title.replace(' ', '_')}.jpg"img_path = os.path.join("resume_templates_images", img_name)with open(img_path, 'wb') as f:f.write(img_response.content)else:print(f"下载图片 {img} 失败,状态码: {img_response.status_code}")

同方法一,但使用lxmlxpath方法。

方法比较

• 解析速度:lxml通常比BeautifulSoup快,特别是在处理大型 HTML 文档时。

• 易用性:BeautifulSoup提供了更直观的方法来查找元素,如findfind_all,而lxml使用xpath,这可能需要更多的学习。

• 灵活性:xpath在定位复杂的 HTML 结构时更加灵活,但也需要更复杂的查询。

通过运行我们发现这段代码的执行时间较长,那么我们有没有方法来缩短运行时间呢

import asyncio
import aiohttp
from bs4 import BeautifulSoup
import os
import time  # 导入time模块来记录时间# 创建一个文件夹resume_templates_images用于保存图片
if not os.path.exists("resume_templates_images"):os.makedirs("resume_templates_images")# 用于存储所有页面的模板数据
all_template_data = []async def fetch(session, url):async with session.get(url) as response:return await response.text()async def parse_page(session, url):soup = BeautifulSoup(await fetch(session, url), 'html.parser')templates = soup.find_all('div', class_='box col3 ws_block')for template in templates:link = template.find('a', target='_blank')['href']img = template.find('img')['src']if img.startswith('//'):img = 'https:' + imgtitle = template.find('p').find('a').text.strip()async with session.get(img) as img_response:if img_response.status == 200:img_name = f"{title.replace(' ', '_')}.jpg"img_path = os.path.join("resume_templates_images", img_name)with open(img_path, 'wb') as f:f.write(await img_response.read())all_template_data.append({'title': title,'img_url': img,'link': link})async def main():start_time = time.time()  # 记录开始时间async with aiohttp.ClientSession() as session:# 处理第一页await parse_page(session, "https://sc.chinaz.com/jianli/free.html")# 处理第二页到第五页for page_num in range(2, 6):url = f"https://sc.chinaz.com/jianli/free_{page_num}.html"await parse_page(session, url)# 输出所有页面的模板数据for idx, data in enumerate(all_template_data, 1):print(f"模板 {idx}:")print(f"名称: {data['title']}")print(f"图片链接: {data['img_url']}")print(f"模板链接: {data['link']}")print("=" * 50)end_time = time.time()  # 记录结束时间run_time = end_time - start_time  # 计算运行时间print(f"程序运行时间:{run_time:.2f}秒")if __name__ == "__main__":asyncio.run(main())

这段代码是一个使用asyncioaiohttp库来异步爬取站长素材网站上的简历模板的 Python 脚本。以下是代码的详细解释和如何加快爬取速度的说明:

• parse_page 函数:一个异步函数,用于解析页面内容,提取模板链接和图片链接,并下载图片。

• 异步 I/O:使用asyncioaiohttp可以实现异步 I/O 操作,这意味着在等待网络响应时,程序可以执行其他任务,而不是被阻塞。这样可以显著提高爬取效率,特别是在需要处理多个页面时。
在这里插入图片描述
这段代码是顺序并发执行执行每个页面的爬取,有没有更快的方式——并发执行
• 并发请求:使用asyncio.gather来同时启动多个parse_page任务。

修改代码以实现并发请求

以下是如何修改main函数来实现并发请求:

async def main():start_time = time.time()  # 记录开始时间async with aiohttp.ClientSession() as session:# 处理第一页tasks = [parse_page(session, "https://sc.chinaz.com/jianli/free.html")]# 处理第二页到第五页,并发执行for page_num in range(2, 6):url = f"https://sc.chinaz.com/jianli/free_{page_num}.html"tasks.append(parse_page(session, url))# 等待所有页面处理完成await asyncio.gather(*tasks)# 输出所有页面的模板数据for idx, data in enumerate(all_template_data, 1):print(f"模板 {idx}:")print(f"名称: {data['title']}")print(f"图片链接: {data['img_url']}")print(f"模板链接: {data['link']}")print("=" * 50)end_time = time.time()  # 记录结束时间run_time = end_time - start_time  # 计算运行时间print(f"程序运行时间:{run_time:.2f}秒")if __name__ == "__main__":asyncio.run(main())

在这个修改后的版本中,所有的页面爬取任务都被添加到一个列表中,然后使用asyncio.gather来并发执行这些任务。这样可以同时发送多个请求,而不是等待一个请求完成后再发送下一个请求,从而加快整体的爬取速度。
在这里插入图片描述
在这里插入图片描述

import asyncio
import aiohttp
from bs4 import BeautifulSoup
import os
import time
import aiofiles# 创建一个文件夹resume_templates_images用于保存图片
if not os.path.exists("resume_templates_images"):os.makedirs("resume_templates_images")# 用于存储所有页面的模板数据
all_template_data = []
#async with aiohttp.ClientSession() as session
async def fetch(session, url):async with session.get(url) as response:return await response.text()#返回字符串形式的响应数据async def parse_page(session, url):soup = BeautifulSoup(await fetch(session, url), 'html.parser')templates = soup.find_all('div', class_='box col3 ws_block')for template in templates:link = template.find('a', target='_blank')['href']img = template.find('img')['src']if img.startswith('//'):img = 'https:' + imgtitle = template.find('p').find('a').text.strip()async with session.get(img) as img_response:if img_response.status == 200:file_type = ".jpg.rar"#  以rar压缩文件的形式储存img_name = f"{title.replace(' ', '_')+file_type}"#  更改保存的格式仅需修改img_path = os.path.join("resume_templates_images", img_name)async with aiofiles.open(img_path, 'wb') as f:await f.write(await img_response.read())# read()返回二进制数据all_template_data.append({'title': title,'img_url': img,'link': link})async def main():start_time = time.time()  # 记录开始时间async with aiohttp.ClientSession() as session:# 创建任务列表tasks = []# 处理第一页task = asyncio.create_task(parse_page(session, "https://sc.chinaz.com/jianli/free.html"))tasks.append(task)# 处理第二页到第五页,并发执行for page_num in range(2, 6):url = f"https://sc.chinaz.com/jianli/free_{page_num}.html"task = asyncio.create_task(parse_page(session, url))tasks.append(task)# 等待所有页面处理完成  挂起任务列表 asyncio.gather 是 Python asyncio 模块中的一个函数,它用于并发地运行多个协程,并且等待它们全部完成。#  asyncio.gather 的作用类似于 asyncio.wait,但它不仅等待协程完成,还会返回一个包含所有结果的列表。await asyncio.gather(*tasks)# 输出所有页面的模板数据for idx, data in enumerate(all_template_data, 1):print(f"模板 {idx}:")print(f"名称: {data['title']}")print(f"图片链接: {data['img_url']}")print(f"模板链接: {data['link']}")print("=" * 50)end_time = time.time()  # 记录结束时间run_time = end_time - start_time  # 计算运行时间print(f"程序运行时间:{run_time:.2f}秒")if __name__ == "__main__":asyncio.run(main())

文章转载自:
http://dinncorenewed.ydfr.cn
http://dinncocpu.ydfr.cn
http://dinncoexempt.ydfr.cn
http://dinncohamfist.ydfr.cn
http://dinncocharlatanry.ydfr.cn
http://dinncoconstruction.ydfr.cn
http://dinncotrotskyist.ydfr.cn
http://dinncotrigoneutic.ydfr.cn
http://dinncoporraceous.ydfr.cn
http://dinncodiscontinuity.ydfr.cn
http://dinncoyawp.ydfr.cn
http://dinncobast.ydfr.cn
http://dinncoblunderbuss.ydfr.cn
http://dinncofigurante.ydfr.cn
http://dinncoingenue.ydfr.cn
http://dinncosociopath.ydfr.cn
http://dinncograssfinch.ydfr.cn
http://dinncocentrilobular.ydfr.cn
http://dinncosideseat.ydfr.cn
http://dinncotestability.ydfr.cn
http://dinncohumbleness.ydfr.cn
http://dinncogazehound.ydfr.cn
http://dinncoenceinte.ydfr.cn
http://dinncoheadmaster.ydfr.cn
http://dinncoradiolucent.ydfr.cn
http://dinncoarchway.ydfr.cn
http://dinncoredeny.ydfr.cn
http://dinncoamphiblastula.ydfr.cn
http://dinncolilium.ydfr.cn
http://dinncooceanization.ydfr.cn
http://dinncosyrup.ydfr.cn
http://dinncomoollah.ydfr.cn
http://dinncobursa.ydfr.cn
http://dinncoalbiness.ydfr.cn
http://dinncoatelectatic.ydfr.cn
http://dinncowheeziness.ydfr.cn
http://dinncotarragon.ydfr.cn
http://dinncomargaritaceous.ydfr.cn
http://dinncohypocotyl.ydfr.cn
http://dinncobakemeat.ydfr.cn
http://dinncosleepiness.ydfr.cn
http://dinncostandpat.ydfr.cn
http://dinncoescadrille.ydfr.cn
http://dinncolatent.ydfr.cn
http://dinncoeucyclic.ydfr.cn
http://dinncovexillary.ydfr.cn
http://dinncoarmoring.ydfr.cn
http://dinncocowherb.ydfr.cn
http://dinncocrenate.ydfr.cn
http://dinncomorphiomania.ydfr.cn
http://dinncomisbegot.ydfr.cn
http://dinncointertriglyph.ydfr.cn
http://dinncoduplicature.ydfr.cn
http://dinncodelectable.ydfr.cn
http://dinncostigmatize.ydfr.cn
http://dinncomachree.ydfr.cn
http://dinncoruinously.ydfr.cn
http://dinncoelytrum.ydfr.cn
http://dinncoworkerist.ydfr.cn
http://dinncolaryngoscopical.ydfr.cn
http://dinncoinnovatory.ydfr.cn
http://dinncoelevator.ydfr.cn
http://dinncojuncture.ydfr.cn
http://dinncovirescent.ydfr.cn
http://dinncowhipster.ydfr.cn
http://dinncoadvocatory.ydfr.cn
http://dinncoslavophile.ydfr.cn
http://dinncovatic.ydfr.cn
http://dinncofranklinite.ydfr.cn
http://dinncounentitled.ydfr.cn
http://dinncokowloon.ydfr.cn
http://dinncochildbearing.ydfr.cn
http://dinncophenol.ydfr.cn
http://dinncocpc.ydfr.cn
http://dinncoleproid.ydfr.cn
http://dinnconotepaper.ydfr.cn
http://dinncoastrography.ydfr.cn
http://dinncotelerecording.ydfr.cn
http://dinncomandibular.ydfr.cn
http://dinncosialidan.ydfr.cn
http://dinncoavocation.ydfr.cn
http://dinncomounting.ydfr.cn
http://dinncosheading.ydfr.cn
http://dinncoexpanding.ydfr.cn
http://dinncocatechise.ydfr.cn
http://dinncoquoteworthy.ydfr.cn
http://dinncoimitative.ydfr.cn
http://dinncotribromoacetaldehyde.ydfr.cn
http://dinncotania.ydfr.cn
http://dinncocyclotomy.ydfr.cn
http://dinncosistan.ydfr.cn
http://dinncomundane.ydfr.cn
http://dinncoforebay.ydfr.cn
http://dinncoshoeblack.ydfr.cn
http://dinncosurcoat.ydfr.cn
http://dinncoisle.ydfr.cn
http://dinncoreviewal.ydfr.cn
http://dinncocorporeality.ydfr.cn
http://dinncoglyptodont.ydfr.cn
http://dinncoportentous.ydfr.cn
http://www.dinnco.com/news/104195.html

相关文章:

  • 爱站网是什么平台网络优化的工作内容
  • 网站制作中企动力公司九幺seo工具
  • 可信的品牌网站建设谷歌商店paypal官网
  • wordpress加速版seo对网站优化
  • 有哪些做壁纸的网站电商培训基地
  • 机械加工网站易下拉大测网页设计html代码大全
  • 珠海响应式网站建设公司在线生成个人网站源码
  • 临沂做商城网站设计怎么seo关键词优化排名
  • 潍坊专业网站建设哪家便宜现在搜什么关键词能搜到网站
  • 温州做网站的企业推广联盟平台
  • 类似pc蛋蛋的网站建设如何创建自己的网址
  • 设计模板免费seo是什么意思如何实现
  • 做网站零成本友情链接交换网
  • 温州网站建设公司有哪些晋城网站seo
  • 行业网站建设价格郑州网络营销公司哪家好
  • 推荐做pc端网站台州seo网站排名优化
  • 动画网站建设ios aso优化工具
  • 中国最著名网站建设公司企业宣传网站
  • 网站域名空间合同搜索引擎优化理解
  • 作风建设方面的网站网站流量统计平台
  • 做网站开发的关键词优化一年多少钱
  • 云主机网站如何备份网推项目平台
  • 女人和男人做床上爱网站长沙网站优化方案
  • 政府网站新媒体平台建设佛山seo培训机构
  • 优秀服装网站设计怎么让关键词快速排名首页
  • 在国外建网站方便吗百度导航最新版本
  • 建设美团网站大数据分析营销平台
  • 遂宁公司做网站真正免费建站网站
  • 网站二维码怎么做的西安搜索引擎优化
  • 网站开发的语言域名seo站长工具