1:urllib urllib.request
这两个库是python自带的库,不需要重新安装,在python中输入如下代码:
import urllib
import urllib.request
response = urllib.request.urlopen("http://www.baidu.com")
print(response)
返回结果为HTTPResponse的对象:
2:request库的安装
安装命令:pip install requests
验证该库是否安装成功,运行如下代码:
import requests
response=requests.get("http://www.baidu.com")
print(response)
返回结果:
3:安装django
pip install django
4:安装flask
pip install flask
5:安装redis
pip install redis
6:安装pymysql
pip install pymysql
7:安装pymongo
pip install pymongo
8:安装beautifulsoup
pip install beautifulsoup4
9:安装LXML
pip install lxml
10:selenium库的安装
pip install selenium
由于如果需要使用selenium的话,需要为本机配置对应浏览器的驱动,下面以chomedriver为例,首先安装chromedriver,chromedriver与支持对应的chrome版本可以在这里面下载:
http://chromedriver.storage.googleapis.com/index.html
下载与浏览器对应的版本
chromedriver解压后把chromedriver.exe放到Python或者其他配置了环境变量的目录下。
测试代码及运行结果如下:
安装plantomjs
下载地址:http://phantomjs.org/download.html
下载完成后,解压文件夹,将文件夹中phantomjs.exe的拷贝到Python或者其他配置了环境变量的目录下,或单独为其配置环境变量,测试代码及运行结果如下:
完成。
简单写了个用selenium爬取斗鱼的程序
爬取直播间的标题,主播,人数
from selenium import webdriver
import time
class DouYu:
def __init__(self):
self.start_url = "https://www.douyu.com/directory/all"
self.driver = webdriver.Chrome()
def get_content_list(self):
li_list = self.driver.find_elements_by_xpath("//ul[@id='live-list-contentbox']/li")
content_list = []
for li in li_list:
item = {}
item["title"] = li.find_element_by_xpath("./a").get_attribute("title")
item["anchor"] = li.find_element_by_xpath(".//span[@class='dy-name ellipsis fl']").text
item["watch_num"] = li.find_element_by_xpath(".//span[@class='dy-num fr']").text
print(item)
content_list.append(item)
next_url = self.driver.find_elements_by_xpath("//a[@class='shark-pager-next']")
next_url = next_url[0] if len(next_url) > 0 else None
return content_list, next_url
def save_content_list(self, content_list):
pass
def run(self): # 实现主要逻辑
# 1, start_url
# 2, 发送请求,获取响应
self.driver.get(self.start_url)
# 3, 提取数据
content_list, next_url = self.get_content_list()
# 4, 保存
self.save_content_list(content_list)
# 5, 下一页数据的提取
while next_url is not None:
next_url.click()
time.sleep(3)
content_list, next_url = self.get_content_list()
self.save_content_list(content_list)
if __name__ == '__main__':
douyu = DouYu()
douyu.run()