爬取豆瓣读书之新书速递(selenium库应用)

Selenium库应用测试

#!/usr/bin/env python3
"""
爬取豆瓣读书新书信息
目标网页:https://book.douban.com/
技术路线:Python,selenium
浏览器:Microsoft Edge
要点:页面元素定位、页面不显示元素内容的获取
"""

from selenium import webdriver


def getContent(marker, tagName):
	# 关键在于页面中不显示标记点内容的读取
	txt = marker.find_element_by_class_name(tagName).get_attribute('textContent').strip()
	return txt


if __name__ == '__main__':
	url = r"https://book.douban.com/"

	driver = webdriver.Edge(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedgedriver.exe")
	driver.maximize_window()  # 最大化窗口
	driver.get(url)

	books = []
	uls = driver.find_elements_by_xpath('//ul')

	for ulItem in uls:
		ulItemClass = ulItem.get_attribute('class')
		if ulItemClass == 'list-col list-col5 list-express slide-item':
			lis = ulItem.find_elements_by_xpath('li')

			for liItem in lis:
				divs = liItem.find_element_by_class_name('more-meta')
				bookName = getContent(divs, 'title')
				author = getContent(divs, 'author')
				publishYear = getContent(divs, 'year')
				publisher = getContent(divs, 'publisher')
				books.append([bookName, author, publishYear, publisher])

	driver.quit()		# 关闭浏览器
	
	for book in books:
		print(book)

你可能感兴趣的:(爬取豆瓣读书之新书速递(selenium库应用))