抓取动态网页(Selenium自动化动态网页的数据代码代码结果四.总结(一))

优采云 发布时间: 2021-12-28 13:10

  抓取动态网页(Selenium自动化动态网页的数据代码代码结果四.总结(一))

  内容

  前言

  学习Selenium自动化测试框架,在Anaconda的虚拟环境中安装selenium和webdrive等必要的库。熟悉浏览器的开发者模式(Chrome和Edge浏览器按F12)分析网页结构,找到对应网页元素的技巧。然后完成以下任务:

  1)自动测试网页。比如在百度网页上自动填写搜索关键词,完成自动搜索。

  2) 爬取一个动态网页的数据,根据附件的要求实现代码。

  3) 抓取京东网站上感兴趣的书籍信息(如关键词“python编程”的前200本书)并保存。

  一.Selenium 1. 简介

  Selenium 是一个 Web 自动化测试工具。它最初是为自动化网站测试而开发的。类型就像我们用来玩游戏的按钮向导。可根据指定指令自动运行。不同的是,Selenium 可以直接在浏览器上运行。支持所有主流浏览器(包括PhantomJS等非接口浏览器)。

  Selenium 可以根据我们的指示让浏览器自动加载页面,获取所需的数据,甚至可以对页面进行截图,或者判断网站上是否发生了某些操作。

  Selenium 没有浏览器,不支持浏览器的功能。需要配合第三方浏览器使用。但是我们有时需要让它嵌入到代码中运行,所以我们可以使用一个叫做 PhantomJS 的工具来代替真正的浏览器。

  2.环境配置

  打开 Anaconda 提示

  conda install selenium

  

  3.安装驱动

  Selenium 官网驱动下载(下载 | Selenium)

  适用于 Chrome 的 ChromeDriver 镜像

  

  

  二. 爬取动态网页的数据

  

  代码

  def write_csv(csv_head,csv_content,csv_path):

with open(csv_path, 'w', newline='',encoding='utf-8') as file:

fileWriter =csv.writer(file)

fileWriter.writerow(csv_head)

fileWriter.writerows(csv_content)

print('爬取信息成功')

quote=driver.find_elements_by_class_name("quote")

#将要收集的信息放在quote_content里

for i in tqdm(range(len(quote))):

quote_text=quote[i].find_element_by_class_name("text")

quote_author=quote[i].find_element_by_class_name("author")

temp=[]

temp.append(quote_text.text)

temp.append(quote_author.text)

quote_content.append(temp)

write_csv(quote_head,quote_content,quote_path)

  

  三. 在京东网站上爬取感兴趣的书籍信息

  代码

<p>driver = webdriver.Chrome("E:\GoogleDownload\chromedriver_win32\chromedriver.exe")

driver.set_window_size(1920,1080)

# 京东网站

driver.get("https://www.jd.com/")

# 输入需要查找的关键字

key=driver.find_element_by_id("key").send_keys("python编程")

time.sleep(1)

# 点击搜素按钮

button=driver.find_element_by_class_name("button").click()

time.sleep(1)

# 获取所有窗口

windows = driver.window_handles

# 切换到最新的窗口

driver.switch_to.window(windows[-1])

time.sleep(1)

# js语句

js = &#39;return document.body.scrollHeight&#39;

# 获取body高度

max_height = driver.execute_script(js)

max_height=(int(max_height/1000))*1000

# 当前滚动条高度

tmp_height=1000

# 所有书籍的字典

res_dict={}

# 需要爬取的数量

num=200

while len(res_dict)

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线