注:本文参考了网易云知了课堂课件笔记。
AJAX(Asynchronouse JavaScript And XML)异步JavaScript和XML。在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。传统的网页(不使用Ajax)如果需要更新内容,必须重载整个网页页面。因为传统的在传输数据格式方面,使用的是XML语法。因此叫做AJAX,其实现在数据交互基本上都是使用JSON。使用AJAX加载的数据,即使使用了JS,将数据渲染到了浏览器中,在右键->查看网页源代码还是不能看到通过ajax加载的数据,只能看到使用这个url加载的html代码。
1.直接分析ajax调用的接口。然后通过代码请求这个接口。
优点:直接可以请求到数据。不需要做一些解析工作。代码量少,性能高。
缺点:分析接口比较复杂,特别是一些通过js混淆的接口,要有一定的js功底。容易被发现是爬虫。
2.使用Selenium+chromedriver模拟浏览器行为获取数据。
优点:直接模拟浏览器的行为。浏览器能请求到的,使用selenium也能请求到。爬虫更稳定。
缺点:代码量多。性能低。
Selenium相当于是一个机器人。可以模拟人类在浏览器上的一些行为,自动处理浏览器上的一些行为,比如点击,填充数据,删除cookie等。chromedriver是一个驱动Chrome浏览器的驱动程序,使用他才可以驱动浏览器。当然针对不同的浏览器有不同的driver。以下列出了不同浏览器及其对应的driver:
Chrome:https://sites.google.com/a/chromium.org/chromedriver/downloads
Firefox:https://github.com/mozilla/geckodriver/releases
Edge:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Safari:https://webkit.org/blog/6900/webdriver-support-in-safari-10/
1.安装Selenium
pip install selenium
2.安装chromedriver
下载完成后,放到不需要权限的纯英文目录下就可以了。
from selenium import webdriver
# chromedriver的绝对路径
driver_path = r'D:\ProgramApp\chromedriver\chromedriver.exe'
# 初始化一个driver,并且指定chromedriver的路径
driver = webdriver.Chrome(executable_path=driver_path)
# 请求网页
driver.get("https://www.baidu.com/")
# 通过page_source获取网页源代码
print(driver.page_source)
更多教程请参考:http://selenium-python.readthedocs.io/installation.html#introduction
1.driver.close():关闭当前页面。
2.driver.quit():退出整个浏览器。
1.find_element_by_id:根据id来查找某个元素。等价于:
submitTag = driver.find_element_by_id('su')
submitTag1 = driver.find_element(By.ID,'su')
2.find_element_by_class_name:根据类名查找元素。 等价于:
submitTag = driver.find_element_by_class_name('su')
submitTag1 = driver.find_element(By.CLASS_NAME,'su')
3.find_element_by_name:根据name属性的值来查找元素。等价于:
submitTag = driver.find_element_by_name('email')
submitTag1 = driver.find_element(By.NAME,'email')
4.find_element_by_tag_name:根据标签名来查找元素。等价于:
submitTag = driver.find_element_by_tag_name('div')
submitTag1 = driver.find_element(By.TAG_NAME,'div')
5.find_element_by_xpath:根据xpath语法来获取元素。等价于:
submitTag = driver.find_element_by_xpath('//div')
submitTag1 = driver.find_element(By.XPATH,'//div')
submitTag = driver.find_element_by_css_selector('//div')
submitTag1 = driver.find_element(By.CSS_SELECTOR,'//div')
要注意,find_element是获取第一个满足条件的元素。find_elements是获取所有满足条件的元素。
1.操作输入框:分为两步。第一步:找到这个元素。第二步:使用send_keys(value),将数据填充进去。示例代码如下:
inputTag = driver.find_element_by_id('kw')
inputTag.send_keys('python')
使用clear方法可以清除输入框中的内容。示例代码如下:
inputTag.clear()
2.操作checkbox:因为要选中checkbox标签,在网页中是通过鼠标点击的。因此想要选中checkbox标签,那么先选中这个标签,然后执行click事件。示例代码如下:
rememberTag = driver.find_element_by_name("rememberMe")
rememberTag.click()
from selenium.webdriver.support.ui import Select
# 选中这个标签,然后使用Select创建对象
selectTag = Select(driver.find_element_by_name("jumpMenu"))
# 根据索引选择
selectTag.select_by_index(1)
# 根据值选择
selectTag.select_by_value("http://www.95yueba.com")
# 根据可视的文本选择
selectTag.select_by_visible_text("95秀客户端")
# 取消选中所有选项
selectTag.deselect_all()
4.操作按钮:操作按钮有很多种方式。比如单击、右击、双击等。这里讲一个最常用的。就是点击。直接调用click函数就可以了。示例代码如下:
inputTag = driver.find_element_by_id('su')
inputTag.click()
有时候在页面中的操作可能要有很多步,那么这时候可以使用鼠标行为链类ActionChains来完成。比如现在要将鼠标移动到某个元素上并执行点击事件。那么示例代码如下:
inputTag = driver.find_element_by_id('kw')
submitTag = driver.find_element_by_id('su')
actions = ActionChains(driver)
actions.move_to_element(inputTag)
actions.send_keys_to_element(inputTag,'python')
actions.move_to_element(submitTag)
actions.click(submitTag)
actions.perform()
还有更多的鼠标相关的操作。
click_and_hold(element):点击但不松开鼠标。
context_click(element):右键点击。
double_click(element):双击。 更多方法请参考:http://selenium-python.readthedocs.io/api.html
1.获取所有的cookie:
for cookie in driver.get_cookies():
print(cookie)
2.根据cookie的key获取value:
value = driver.get_cookie(key)
3.删除所有的cookie:
driver.delete_all_cookies()
driver.delete_cookie(key)
现在的网页越来越多采用了 Ajax 技术,这样程序便不能确定何时某个元素完全加载出来了。如果实际页面等待时间过长导致某个dom元素还没出来,但是你的代码直接使用了这个WebElement,那么就会抛出NullPointer的异常。为了解决这个问题。所以 Selenium 提供了两种等待方式:一种是隐式等待、一种是显式等待。
1.隐式等待:调用driver.implicitly_wait。那么在获取不可用的元素之前,会先等待10秒中的时间。示例代码如下:
driver = webdriver.Chrome(executable_path=driver_path)
driver.implicitly_wait(10)
# 请求网页
driver.get("https://www.douban.com/")
2.显示等待:显示等待是表明某个条件成立后才执行获取元素的操作。也可以在等待的时候指定一个最大的时间,如果超过这个时间那么就抛出一个异常。显示等待应该使用selenium.webdriver.support.excepted_conditions期望的条件和selenium.webdriver.support.ui.WebDriverWait来配合完成。示例代码如下:
rom selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
finally:
driver.quit()
3.一些其他的等待条件:
presence_of_element_located:某个元素已经加载完毕了。
presence_of_all_emement_located:网页中所有满足条件的元素都加载完毕了。
element_to_be_cliable:某个元素是可以点击了。
更多条件请参考:http://selenium-python.readthedocs.io/waits.html
有时候窗口中有很多子tab页面。这时候肯定是需要进行切换的。selenium提供了一个叫做switch_to_window来进行切换,具体切换到哪个页面,可以从driver.window_handles中找到。示例代码如下:
# 打开一个新的页面
self.driver.execute_script("window.open('"+url+"')")
# 切换到这个新的页面中
self.driver.switch_to_window(self.driver.window_handles[1])
有时候频繁爬取一些网页。服务器发现你是爬虫后会封掉你的ip地址。这时候我们可以更改代理ip。更改代理ip,不同的浏览器有不同的实现方式。这里以Chrome浏览器为例来讲解:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--proxy-server=http://110.73.2.248:8123")
driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
driver = webdriver.Chrome(executable_path=driver_path,chrome_options=options)
driver.get('http://httpbin.org/ip')
from selenium.webdriver.remote.webelement import WebElement类是每个获取出来的元素的所属类。
有一些常用的属性:
1.get_attribute:这个标签的某个属性的值。
2.screentshot:获取当前页面的截图。这个方法只能在driver上使用。
driver的对象类,也是继承自WebElement。
更多请阅读相关源代码。
import time
import re
from lxml import etree
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import csv
class LagouSpider(object):
driver_path = r'/home/kiosk/Desktop/chromedriver'
def __init__(self):
self.driver = webdriver.Chrome(executable_path=self.driver_path)
self.url = 'https://www.lagou.com/jobs/list_python?isSchoolJob=1'
self.positions = []
self.fp = open('lagou.csv','a',encoding='utf-8',newline='')
self.writer = csv.DictWriter(self.fp,[
'name','company_name','salary','city','work_years','education','desc'
])
self.writer.writeheader()
def run(self):
self.driver.get(self.url)
while True:
source = self.driver.page_source
WebDriverWait(driver=self.driver,timeout=10).until(
EC.presence_of_all_elements_located((By.XPATH,
"//div[@class='pager_container']/span[last()]"))
)
self.parse_list_page(source)
try:
next_btn = self.driver.find_element_by_xpath(
"//div[@class='pager_container']/span[last()]")
if "pager_next_disabled" in next_btn.get_attribute("class"):
break
else:
next_btn.click()
except:
print(source)
time.sleep(1)
def parse_list_page(self,source):
html = etree.HTML(source)
links = html.xpath("//a[@class='position_link']/@href")
for link in links:
self.request_detail_page(link)
time.sleep(1)
def request_detail_page(self,url):
self.driver.execute_script("window.open('%s')"%url)
self.driver.switch_to.window(self.driver.window_handles[1])
WebDriverWait(self.driver,timeout=10).until(
EC.presence_of_all_elements_located(
(By.XPATH,"//div[@class='job-name']/span[@class='name']"))
)
source = self.driver.page_source
self.parse_detail_page(source)
self.driver.close()
self.driver.switch_to.window(self.driver.window_handles[0])
def parse_detail_page(self,source):
html = etree.HTML(source)
position_name = html.xpath("//span[@class='name']/text()")[0]
job_request_spans = html.xpath("//dd[@class='job_request']//span")
salary = job_request_spans[0].xpath('.//text()')[0].strip()
city = job_request_spans[1].xpath(".//text()")[0].strip()
city = re.sub(r"[\s/]", "", city)
work_years = job_request_spans[2].xpath(".//text()")[0].strip()
work_years = re.sub(r"[\s/]", "", work_years)
education = job_request_spans[3].xpath(".//text()")[0].strip()
education = re.sub(r"[\s/]", "", education)
desc = "".join(html.xpath("//dd[@class='job_bt']//text()")).strip()
company_name = html.xpath("//h2[@class='fl']/text()")[0].strip()
position = {
'name': position_name,
'company_name': company_name,
'salary': salary,
'city': city,
'work_years': work_years,
'education': education,
'desc': desc
}
self.write_position(position)
def write_position(self,positon):
if len(self.positions) >= 20:
self.writer.writerows(self.positions)
self.positions.clear()
self.positions.append(positon)
print(positon)
if __name__ == '__main__':
spider = LagouSpider()
spider.run()
import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import csv
from lxml import etree
class BossSpider(object):
driver_path = r'/home/kiosk/Desktop/chromedriver'
def __init__(self):
self.driver = webdriver.Chrome(executable_path=BossSpider.driver_path)
self.url = 'https://www.zhipin.com/job_detail/?query=python&city=100010000&industry=&position='
self.positions = []
self.fp = open('boss.csv','a',encoding='utf-8',newline='')
self.writer = csv.DictWriter(self.fp,['position_name','salary','city','work_years','education','desc','company_name'])
self.writer.writeheader()
def run(self):
self.driver.get(self.url)
while 1:
source = self.driver.page_source
# WebDriverWait(self.driver,timeout=10).until(
# EC.presence_of_all_elements_located((By.XPATH,"//a[contains(@class,'next')"))
# )
self.parse_list_page(source)
try:
next_btn = self.driver.find_element_by_xpath("//a[contains(@class,'next')]")
if 'disabled' in next_btn.get_attribute('class'):
break
else:
next_btn.click()
except:
print(source)
time.sleep(1)
def parse_list_page(self,source):
html = etree.HTML(source)
links = html.xpath("//div[@class='info-primary']//a[position()=1]/@href")
for link in links:
url = 'https://www.zhipin.com'+link
self.request_detail_page(url)
time.sleep(1)
def request_detail_page(self,url):
self.driver.execute_script("window.open('%s')"%url)
self.driver.switch_to.window(self.driver.window_handles[1])
WebDriverWait(self.driver,timeout=10).until(
EC.presence_of_all_elements_located((By.XPATH,"//div[@class='name']"))
)
source = self.driver.page_source
self.parse_detail_page(source)
self.driver.close()
self.driver.switch_to.window(self.driver.window_handles[0])
def parse_detail_page(self,source):
html = etree.HTML(source)
position_name = html.xpath("//div[@class='name']/h1/text()")[0]
salary = html.xpath("//div[@class='name']/span[@class='salary']/text()")[0]
city_workyears_education = html.xpath("//div[@class='info-primary']/p/text()")
city = city_workyears_education[0]
work_years = city_workyears_education[1]
education = city_workyears_education[2]
desc = ''.join(html.xpath("//div[@class='job-sec']/div[@class='text']/text()")).strip()
company_name = html.xpath("//div[@class='job-sec']/div[@class='name']/text()")[0]
position = {
'position_name':position_name,
'salary':salary,
'city':city,
'work_years':work_years,
'education':education,
'desc':desc,
'company_name':company_name
}
self.write_postion(position)
def write_postion(self,postion):
if len(self.positions) >= 10:
self.writer.writerows(self.positions)
self.positions.clear()
self.positions.append(postion)
print(postion)
if __name__=='__main__':
bossspider = BossSpider()
bossspider.run()
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class QiangpiaoSpider(object):
driver_path = r'/home/kiosk/Desktop/chromedriver'
def __init__(self):
self.driver = webdriver.Chrome(executable_path=QiangpiaoSpider.driver_path)
self.login_url = 'https://kyfw.12306.cn/otn/login/init'
self.index_url = 'https://kyfw.12306.cn/otn/view/index.html'
self.search_url = 'https://kyfw.12306.cn/otn/leftTicket/init'
self.passengers_url = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
def wait_input(self):
self.from_station = input("出发地:")
self.to_station = input("目的地:")
# 时间格式必须是:yyyy-MM-dd的方式
self.depart_time = input("出发日期:")
self.passengers = input("乘客姓名(如有多个乘客,用英文逗号隔开:").split(",")
self.trains = input("车次(如果有多个车次,用英文逗号隔开:").split(",")
def _longin(self,url):
self.driver.get(url)
WebDriverWait(self.driver,timeout=1000).until(
EC.url_to_be(self.index_url)
)
print("登陆成功!")
def _order_ticket(self):
self.driver.get(self.search_url)
WebDriverWait(self.driver,1000).until(
EC.text_to_be_present_in_element_value(
(By.ID,"fromStationText"),self.from_station
)
)
WebDriverWait(self.driver, 1000).until(
EC.text_to_be_present_in_element_value(
(By.ID, "toStationText"), self.to_station
)
)
WebDriverWait(self.driver, 1000).until(
EC.text_to_be_present_in_element_value(
(By.ID, "train_date"), self.depart_time
)
)
WebDriverWait(self.driver,1000).until(
EC.element_to_be_clickable((By.ID,'query_ticket'))
)
searchBtn = self.driver.find_element_by_id("query_ticket")
searchBtn.click()
WebDriverWait(self.driver,1000).until(
EC.presence_of_all_elements_located((By.XPATH,".//tbody[@id='queryLeftTable']/tr"))
)
tr_list = self.driver.find_elements_by_xpath(".//tbody[@id='queryLeftTable']/tr[not(@datatran)]")
print(tr_list)
for tr in tr_list:
train_number = tr.find_element_by_class_name("number").text
if train_number in self.trains:
left_ticket = tr.find_element_by_xpath(".//td[8]").text
print(left_ticket)
if left_ticket == "有" or left_ticket.isdigit:
orderBtn = tr.find_element_by_class_name("btn72")
orderBtn.click()
WebDriverWait(self.driver,1000).until(
EC.url_to_be(self.passengers_url)
)
WebDriverWait(self.driver,1000).until(
EC.presence_of_all_elements_located((By.XPATH,".//ul[@id='normal_passenger_id']/li"))
)
passenger_labels = self.driver.find_elements_by_xpath(".//ul[@id='normal_passenger_id']/li/label")
for passenger_label in passenger_labels:
name = passenger_label.text
if name in self.passengers:
passenger_label.click()
submitBtn = self.driver.find_element_by_id("submitOrder_id")
submitBtn.click()
WebDriverWait(self.driver, 1000).until(
EC.presence_of_element_located((By.CLASS_NAME, "dhtmlx_wins_body_outer"))
)
WebDriverWait(self.driver,1000).until(
EC.presence_of_all_elements_located((By.ID,"qr_submit_id"))
)
confirmBtn = self.driver.find_element_by_id("qr_submit_id")
while confirmBtn:
confirmBtn.click()
confirmBtn = self.driver.find_element_by_id("qr_submit_id")
return
def run(self):
self.wait_input()
self._longin(self.login_url)
self._order_ticket()
if __name__=='__main__':
qiangpiao = QiangpiaoSpider()
qiangpiao.run()