正式决定当程序员的第二天
劳累的一天结束啦,明天工程师就会带我捋一遍开发采集阶段的系统框架,今天摸鱼的间隙学习了一下selenium lxml re和requests库,收获还不错!
1、error
总结一下碰到的error
1)WebDriverException: Message: ‘chromedriver’ executable needs to be in PATH.
这个问题下载一个chromdriver就好啦,系统问题配置起来有点麻烦
http://npm.taobao.org/mirrors/chromedriver/91.0.4472.19/
2)[Errno 86] Bad CPU type in executable: ‘chromedriver’
多下几个试试,可能是32或64位选错的
3)WebDriverException: Message: unknown error: Runtime.executionContextCreated has invalid ‘context’:
(Session info: chrome=90.0.4430.212)
(Driver info: chromedriver=2.9.248307,platform=Mac OS X 10.13.6 x86_64)
Chrome的版本要和chromedriver一致
4)NoSuchElementException Traceback (most recent call last)
选择的按钮错误
2、学习概括
1)selenium库
刚学的库,小难,花了比较多的时间学习控制浏览器、鼠标事件、键盘事件、获取断言信息等操作。
同时找内容 find_element_by_id/name/class name/tag name/xpath/css_selector/link比自己原来正则表达式快蛮多的。
我觉得比较完整有用的学习链接附上:
selenium自动化测试实战
Python Selenium库的使用
2)requests库
这个比较常用的,代码附在结尾,就这应该够用了
3)re库
温习一下常用的findal函数,参数re.S和findilter
re(正则表达式)详细总结
4)lxml库
依靠etree.parse读取网页,或用etree.HTML()将字符串转成html文档,用.xpath路径选择内容,也不是很难。
Python中lxml库的用法
3小结
结尾是一点练习的代码,和用漂亮汤爬的一点网址,明天看看复习什么,数据库什么的也要学,加油吧。
import selenium
from selenium import webdriver
driver = webdriver.Chrome()
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
c=webdriver.Chrome()
c.get('http://www.agri.cn')
time.sleep(5)
#c.find_element_by_link_text("首页").click()
c.find_element_by_link_text("农业要闻").click()
#c.find_element_by_css_selector(u"[title]=江西").click()
c.current_url
c.get_log('browser')
c.get_window_position()
c.page_source
c.get_screenshot_as_base64()
c.execute_script("alert('hello')")
time.sleep(3)
#c.quit()
c.get_cookie('BAIDUID')
c.get_cookies()
for y in c.get_cookies():
x=y
if x.get('expiry'):
x.pop('expiry')
c.add_cookie(x)
c.delete_cookie('BAIDUID')
c.delete_all_cookies()
c.title
c.name
c.implicitly_wait(5)
c.find_element_by_css_selector("html > body")
c.get_cookies()
import requests
html="http://www.baidu.com"
headers={'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36'}
response=requests.get(html,headers=headers)
response.encoding='utf-8'
html_text=response.text
html_text
from bs4 import BeautifulSoup
import requests
import re
html_url = "http://www.pharmnet.com.cn/sitemap/"#医药网
def text_get(html):
headers={'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36'}
response=requests.get(html,headers=headers)
response.encoding='GBK'
html_text=response.text
soup = BeautifulSoup(html_text,'lxml')
return soup
urls=[]
html_list=text_get(html_url)
for i in html_list:
soup1=BeautifulSoup(str(i),'html.parser')
url = soup1.find('a')['href']
urls.append(url)
urls
#正式实习的第一天