【爬虫】爬取豆瓣图书TOP250

通过xpath定位元素

使用xpath定位元素有好几种方法

// 是从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
 
#!/user/bin/env python
#coding:utf-8
#先是从selenium导入webdriver,然后用webdriver打开安装好的谷歌浏览器。
from selenium import webdriver
#打开chrom浏览器
browser =webdriver.Chrome()
#访问豆瓣
browser.get('https://book.douban.com/top250?icn=index-book250-all')



#得到标题
title=browser.find_element_by_xpath("//div[@id='content']//h1").text
#打印标题
print(title)
#获得当前页面图书信息的元素对象的列表,总共有25条
book_list=browser.find_elements_by_xpath("//tr[@class='item']")
for ele in book_list:
    print(ele.text+"\n")

因为有很多条信息,所以要注意是find_elements_by_xpath哦~

翻页

定位 后页 这个元素

使用find_element_by_class_name来定位这一元素

#!/user/bin/env python
#coding:utf-8
#先是从selenium导入webdriver,然后用webdriver打开安装好的谷歌浏览器。
from selenium import webdriver
import time
#打开chrom浏览器
browser =webdriver.Chrome()
#访问豆瓣
browser.get('https://book.douban.com/top250?icn=index-book250-all')


for i in range(10):
    #得到标题
    title=browser.find_element_by_xpath("//div[@id='content']//h1").text
    #打印标题
    print(title)
    #获得当前页面图书信息的元素对象的列表,总共有25条
    book_list=browser.find_elements_by_xpath("//tr[@class='item']")
    for ele in book_list:
        print(ele.text+"\n")
    #输出当前页数
    print("------------第%s页------------"%(i+1))

    #下一页
    next_page=browser.find_element_by_class_name("next").click()
    time.sleep(5)
    print("\n")

time库则是python的一个标准库

time sleep() 函数推迟调用线程的运行,图中的5表示推迟执行5秒

因为页面的加载需要时间,试想一下,你点击下一页以后立刻开始定位元素,而那个时候元素还没有加载完成,那么程序就容易报错了。

猜你喜欢

转载自www.cnblogs.com/Kohinur/p/10350693.html