赞
踩
在当今信息爆炸的时代,爬虫技术成为高效获取互联网数据的关键工具。本文为初学者精心打造了一份入门级爬虫指南,从基础概念、常用库介绍到实战案例分享,全方位覆盖爬虫技术的核心要点。通过学习本文,你将掌握爬虫的基本步骤、requests、BeautifulSoup、selenium等工具的使用及实战技巧,并了解在爬虫过程中应遵守的法律法规和道德准则。无论你是编程爱好者还是数据分析师,本文都能助你快速入门爬虫技术,开启数据收集与分析的新篇章。
Python 爬虫(Web Scraping 或 Web Crawling)是一种自动化程序,用于从互联网上抓取或提取数据。Python 由于其简洁的语法、丰富的库支持以及强大的社区,成为了实现爬虫功能的热门选择。下面将简要介绍Python爬虫的基本概念、常用库以及一些基本步骤。
requests
: 用于发送HTTP请求,是爬虫中常用的库之一。
BeautifulSoup
: 用于从HTML或XML文件中提取数据,通过解析文档为用户提供需要抓取的数据。
Scrapy
: 一个快速高级的Web抓取和网页抓取框架,用于爬取网站并从页面中提取结构化的数据。Scrapy使用Twisted异步网络框架来处理网络通讯。
Selenium
: 一个用于Web应用程序测试的工具,支持多种浏览器和平台。它可以直接模拟用户操作浏览器,非常适合需要JavaScript渲染的网页。
lxml
: 一个高效的HTML和XML解析库,支持XPath和XSLT。
requests
发送HTTP请求获取网页内容。BeautifulSoup
、lxml
或Scrapy
解析网页,提取所需数据。Selenium
。requests-get请求:
import requests
# 发送GET请求
url = 'https://www.baidu.com'
response = requests.get(url)
response.encoding = response.apparent_encoding # 使用其自动检测到的最合适的编码方式来解码响应内容
# 处理响应
print(response.status_code) # 获取响应状态码
print(response.text) # 以字符串形式获取响应体
# print(response.json()) # 如果响应体是JSON格式,可以直接解析为Python字典或列表
requests-post请求
import requests
# 发送POST请求
data = {'key': 'value'}
response = requests.post('https://httpbin.org/post', data=data)
# ... 处理响应 ...
print(response.status_code) # 获取响应状态码
print(response.text) # 以字符串形式获取响应体
print(response.json()) # 如果响应体是JSON格式,可以直接解析为Python字典或列表
import requests from bs4 import BeautifulSoup url = "https://www.gushiwen.cn/shiwens/" resp = requests.get(url) if resp.status_code != 200: print("请求失败") resp.encoding = resp.apparent_encoding soup = BeautifulSoup(resp.text, "html.parser") div_list = soup.select("#leftZhankai > div.sons") for div in div_list: title = div.select("div.cont > div:nth-child(2) > p > a > b")[0].string name = div.select("div.cont > div:nth-child(2) > p.source > a > img")[0].get("alt") pic = div.select("div.cont > div:nth-child(2) > p.source > a > img")[0].get("src") # 使用str.format进行对齐,保留20个空格的宽度 print("{:<20} {} {}".format(title, name, pic))
import requests
from bs4 import BeautifulSoup
url = "https://www.meishij.net/caixi/lucai/"
resp = requests.get(url)
resp.encoding = resp.apparent_encoding
soup = BeautifulSoup(resp.text, "html.parser")
div_list = soup.select("body > div.main_w.clearfix > article > div.list_s2 > div.list_s2_content > div")
for div in div_list:
dish_name = div.select("a > strong")[1].string
ingredients = div.select("a > span")[0].string
print("菜名:",dish_name,end="-------------")
print("原材料:",ingredients)
import requests from bs4 import BeautifulSoup import json import os base_path = "D:\Gtop\AHA\myvideos" url = "https://www.meishij.net/video/" resp = requests.get(url) # print(resp.status_code) # print(resp.text) # print(resp.content) soup = BeautifulSoup(resp.text, "html.parser") video_list = soup.select("#v_list > div.v_item") print(len(video_list)) for video in video_list: video_href = video.select_one("a").get("href") # print(video_href) resp_video = requests.get(video_href) soup_video = BeautifulSoup(resp_video.text, "html.parser") video_url = soup_video.select_one("#msj_video").get("src") print(video_url) ret_video = requests.get(video_url) video_path = os.path.join(base_path, video_href.split("/")[-1].split(".")[0]+".mp4") with open(video_path, "wb") as f: f.write(ret_video.content) print(video_path,"下载成功...")
import requests
import json
import os
base_path = "D:\Gtop\AHA\imgs"
url = "https://pic-bucket.ws.126.net/photo/0008/2022-06-13/H9OM3FK2S5L70008NOS.jpg?imageView&thumbnail=300y225"
resp = requests.get(url)
print(resp.content) #二进制内容
pic_name = url.split("/")[-1].split("?")[0]
file_path = os.path.join(base_path,pic_name)
with open(file_path,"wb") as f:
f.write(resp.content)
import requests
url = 'https://baidu.com'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'
}
ip_pool = {
'http': '218.87.205.225:19170',
}
resp = requests.get(url, headers=headers, proxies=ip_pool)
print(resp.status_code)
也可使用fake_useragent,伪造ua:
import fake_useragent
ua = fake_useragent.UserAgent()
print(ua.random)
# 输出:Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36
import requests import json import os base_path = "D:\Gtop\AHA\imgs" # 可以直接从下面接口中拿到数据的 url = "https://product.auto.163.com/rank/api/duration" hd = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'} resp = requests.get(url) print("resp.request.headers---",resp.request.headers) data = json.loads(resp.text) # print(resp.content) for item in data['result']: chexi_name = item['chexi_name'] chexi_photo_white = item['chexi_photo_white'] print(chexi_name, chexi_photo_white) pic_name = item['chexi_photo_white'].split('/')[-1].split('?')[0] file_path = os.path.join(base_path, pic_name) # 请求图片 r_img = requests.get(item['chexi_photo_white']) with open(file_path, 'wb') as f: f.write(r_img.content) print(f"车系:{chexi_name},{pic_name}下载成功!")
import time from selenium import webdriver from selenium.webdriver.common.by import By browser = webdriver.Chrome() browser.get("https://www.baidu.com") print(browser.title) #获取网页的标题 src = browser.find_element(By.ID,"s_lg_img").get_attribute("src") print(src) #获取百度logo的src地址 # 定位到搜索框,向搜索框输入内容 browser.find_element(By.ID, "kw").send_keys("abcdefg") #点击百度一下按钮 browser.find_element(By.ID,"su").click() time.sleep(60*60*24) # 输出: # 百度一下,你就知道 # https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png
# import requests from bs4 import BeautifulSoup import time # import json # url = "https://dashscope.console.aliyun.com/data/api.json?action=ListUseModels&product=dashscope-console&_tag=" # headers = { # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36", # "Cookie": "t=631b97006f3fe62c25c730e5b215f900; login_current_pk=1333082122782615; yunpk=1333082122782615; currentRegionId=cn-hangzhou; tongyi_guest_ticket=40RZObgNrRX*cqHExMqtvRix7leSaU_*gVJ5TgK6swhe03u6yQ5Qc2oDc8uU_yWEm8nW$JCLpIOj0; tongyi_sso_ticket=5E_fb*zzp_8Gn1gsBy1ogROHqapzX0Ccdoyjng$ZacqABBuwXb4xTQVBMHzcrKUAZpZ9VMPUbwuz0; channel=cywf456fmfAutgp66hVf7f2VzCdE4JYIsBnjm%2B6O3fi2fXF5h6q56LYuPc9dxADvL%2BekMN0ZagoRDtPaUg1mAw%3D%3D; cna=lC76F8dphWMCAW+je/ernQ42; _uab_collina=172172179858810191629785; _umdata=G303F989AF3E4FC951911EDA814C72C867C2DB2; cnaui=1719748536469290001; aui=1719748536469290001; sca=924a6421; _samesite_flag_=true; login_aliyunid_ticket=fyKpeu*0vCmV8s*MT5tJl3_1$$wbRxrU8lkjdMu1soaUcn05MXRAAyuSRjQSjsQj9CAj_f_8NpoU_BOTwChTBoNM1ZJeedfK9zxYnbN5hossqIZCr6t7SGxRigm2Cb4fGaCdBZWIzmgdHq6sXXZQg4WF0; login_aliyunid_pk=1333082122782615; hssid=CN-SPLIT-ARCEByIOc2Vzc2lvbl90aWNrZXQyAQE4qsqXjpEyQAFKELnmoY_PdWAVsCf39ATNCapRKRONFVcduL936ppM3YRMxb7cjw; hsite=6; aliyun_country=CN; partitioned_cookie_flag=doubleRemove; aliyun_lang=zh; login_aliyunid_csrf=_csrf_tk_1928322580068200; login_aliyunid=HAHAHa****; aliyun_cert_type_common=1; help_csrf=EO6Xp%2F9TG7eee8xY3kYM1KtFTbpOYlCAxfIqHq1yA7KUkOzHPlOeH32N%2Ba4%2F2xPrKWLPv0sthsf0BlhE35zN%2Fj7JHWzs1r6eV46tmaGMIDYOucM30Pf17406KXlSXg8E2xp2W%2BYrm%2F9bQRXVOFCpNA%3D%3D; cr_token=a748bab5-0a3e-450f-9bc3-dd3b37796fcd; atpsida=18185f8c00bb78974abbecdb_1722580219_6; tfstk=fKHmT9XqhjPb2KS9oY2X650CozR-hZw_ZVBTWRUwazzSBnaxBPzizclY_Ig9IdoKy5kYHm3lcY0hBtLXGcWgBR8pJppKcnw_QenwvWGcllqdQdFNgTJ4lAJMJppK0IrbB08pf2-Z3PraQoPa78-uckf4QSPN43qaXZ5N3VoyqlazbZWVg7ozfkXV_jb2grMZUY843auWwzuSEoVywmzylXkzmS4E0xb5Pgq0iyo4reeYjtFrf5D1fOVi0Xg_Yq72SPMo4xlE8UCYuXqivfm23TyxhmlU_v81_mwYo8kqtGWZq-4xSA05oU4Eh0kQU7pex0kSkmMoXGJa22UrcxyMLHw03ryuVAL53Pcr_xFbCZ8g5Ymr3fjrr_5FFDW_4hHP11N4Vu4B9nFgzS6d_Pxkq6-_guZbJ3xl11N4Vu4pq3feGSr7cyC..; isg=BKys-lqy5tN_gfTgdJsx-nKffYreZVAPeSXaGAbtuNf6EUwbLnUgn6KnMdmpmYhn" # } # response = requests.post(url, headers=headers) # print(response.status_code) # print(response.json()) from selenium import webdriver url = "https://dashscope.console.aliyun.com/overview" # url = "https://blog.csdn.net/m0_48173416?type=blog" driver = webdriver.Chrome() driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { "source": "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})" }) driver.get(url) # print(driver.page_source) time.sleep(20) # 等待页面JS渲染完成 print("soup") soup = BeautifulSoup(driver.page_source, "html.parser") # print(soup) # HAHAHa1122 # q1w2e3r4t5 data = soup.select("#app > div.sc-bdVaJa.hMdjPy.wind-rc-app-layout.windcc-app-layout > div.sc-bZQynM.jexhMp.windcc-app-layout__content > div > div > div.sc-1juic4-0.sc-1bsfzqf-0.dPhReS > div > div > div.components-Layout-___index-scoped__over-left-zero___CCNQj > div:nth-child(2) > div > div > div.next-card-body > div > div > div:nth-child(1) > div > table > tbody > tr.next-table-row.first > td:nth-child(4) > div > div") # data = soup.select("#uid > span") #name print(len(data)) print(data[0].text) #------------------------------------------------------------ #输出: #>>>soup #>>>1 #>>>953461/1000000
#导入selenium库 from selenium import webdriver # 在这里导入浏览器设置相关的类 from selenium.webdriver.chrome.options import Options # from selenium.webdriver.edge.options import Options # ---------------无可视化界面设置(无头模式设置开始)-------------------------------- # chrome_options = Options() # 使用无头模式 chrome_options.add_argument('--headless') # 禁用GPU,防止无头模式出现莫名的BUG chrome_options.add_argument('--disable-gpu') # 将参数传给浏览器 browser = webdriver.Edge(options=chrome_options) # ---------------无可视化界面设置(无头模式设置结束),下面可以正常写代码了------------- # # 启动浏览器 url = "https://baidu.com" browser.get(url) print(browser.title) # 关闭浏览器 browser.quit()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。