1、简述
python编一个爬虫小程序示例。通过爬取有道翻译网站页面信息,获取查询的英语单词的音标。
有道翻译网站url:https://fanyi.youdao.com/#/
2、工具软件
代码编写及测试软件:python3.12(python3.8.9)
selenium库 版本4.16.0
浏览器:chrome浏览器测试版
chrome浏览器驱动:chromedriver.exe
3、代码
(1)打开谷歌浏览器.py
import os
# 打天外部谷歌浏览器 port为tcp端口
def open_chrome(port):
#启动浏览器并开启远程调试
#启动chrom浏览器,并开启port调试端口,该浏览器配置文件路径chrome\temp。对于--remote-debugging-port值,可以指定任何打开(0到65535)的端口。
os.popen(r"start chrome\chrome.exe --remote-debugging-port={} --user-data-dir=temp".format(port))
(2)爬取英语单词音标函数.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from time import sleep
#爬取单词音标函数 port外部谷歌浏览器tcp端口
def fangyi_youdao(port,word):
#实例ch_options对象 ChromeOptions是chromedriver支持的浏览器启动选项
ch_options = webdriver.ChromeOptions()
# 通过端口port接管已打开的外部谷歌浏览器
ch_options.add_experimental_option("debuggerAddress", f"127.0.0.1:{port}")
#添加User-Agent Python的反爬虫机制
ch_options.add_argument('User-Agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"')
# 禁用图片加载
ch_options.add_argument('blink-settings=imagesEnabled=false')
# 启动时,不激活(前置)窗口
ch_options.add_argument('no-startup-window')
# 禁用gpu渲染
ch_options.add_argument('disable-gpu')
#指定chromedriver.exe路径 chromedriver用于连接Chrome浏览器的驱动程序
service = Service(executable_path=r'chrome\chromedriver.exe')
#实例谷歌浏览器对象 Chrome浏览器的WebDriver对象
driver = webdriver.Chrome(service=service, options=ch_options)
# driver.refresh()
#设置隐式等待时间训5秒。如果找不到元素,webdriver会等待5秒,直到元素出现或超时。
driver.implicitly_wait(5)
#设置浏览器 打开的位置 高度 宽度
driver.set_window_rect(0, 0, 1290, 800)
#打开有道翻译
driver.get('https://fanyi.youdao.com/#/')
# “翻译”按钮元素定位
d=driver.find_element(By.XPATH,'//*[@id="app"]/div[1]/div/div[2]/div[2]/div/div[1]/div[1]/div[1]/div[1]/div[1]')
#模拟单击“翻译”按钮
d.click()
#翻译文本录入框 元素定位
d_word=driver.find_element(By.XPATH,'//*[@id="js_fanyi_input"]')
#清空文本录入框
d_word.clear()
#模拟键盘录入要查询单词
d_word.send_keys(word)
sleep(1)
#显示 单词音标的元素定位
d_con=driver.find_element(By.XPATH,'//*[@id="app"]/div[1]/div/div[2]/div[2]/div/div[1]/div[1]/div[2]/div/div[2]/div[1]/div/div[1]/div[1]/ul')
#返回单词音标
return d_con.text.replace('\n','/' )+"/"
(3)检查端口是否占用.py
import socket
def check_port(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1', port))
if result == 0:
# print(f"端口 {port} 已在使用中")
return 0
else:
# print(f"端口 {port} 未被使用")
return 1
(4)控制程序.py
from 打开谷歌浏览器 import *
from 爬取英语单词音标函数 import *
from 检查端口是否占用 import *
#控制端口
port=60000
#端口检测
if check_port(port):
#打开谷歌浏览器
open_chrome(port)
#等待查询单词列表
words_list=['hello','world','well','check','print']
#爬取音标
for word in words_list:
try:
print(f'{word}<-->',fangyi_youdao(port,word))
except:
print(f'{word}查询异常')
continue
print('完成!')