''' 终极版 ''' def get_good(driver): line = 1 try: time.sleep(12) #下拉滑动5000px js_code = ''' window.scrollTo(0,5000) ''' driver.execute_script(js_code) #等待5秒商品加载 time.sleep(5) good_list = driver.find_elements_by_class_name('gl-item') for good in good_list: # 商品名称 good_name = good.find_element_by_css_selector('.p-name em').text # 商品链接 good_url = good.find_element_by_css_selector('.p-name a').get_attribute('href') # 商品价格 good_price = good.find_element_by_class_name('p-price').text # 商品评价 good_commit = good.find_element_by_class_name('p-commit').text good_content = f''' 第{line}个商品 商品名称:{good_name} 商品链接:{good_url} 商品价格:{good_price} 商品评价:{good_commit} \n \n ''' print(good_content) with open('jd5.txt', 'a', encoding='utf-8') as f: f.write(good_content) line += 1 print('下载完成') #找到下一页并点击 next_tag = driver.find_elements_by_class_name('pn-next') next_tag.click() time.sleep(5) get_good(driver) finally: driver.close() if __name__ == '__main__': driver = webdriver.Chrome(r'C:\Users\Administrator\Desktop\chromedriver.exe') try: driver.implicitly_wait(10) driver.get('http://www.jd.com/') input_tag = driver.find_element_by_id('key') input_tag.send_keys('墨菲定律') input_tag.send_keys(Keys.ENTER) get_good(driver) finally: driver.close()