一段自动抓取互联网信息的程序,从互联网上抓取对于咱们有价值的信息html
列表中的每一个元素都是可变的; 列表的元素都是有序的,也就是说每一个元素都有对应的位置; 列表能够容纳全部的对象;python
list = ['波波', '90, '超哥', '小明'] print(list[0]) print(list(2:)) # result 波波 ['超哥', '小明'] # 若是为切片返回的也是列表的数据结构 复制代码
user_info = {
'name': '小明',
'age': '23',
'sex': 'male'
}
复制代码
在爬虫中元组和集合不多用到,这里只作简单的介绍; 元组: 相似于列表,可是元组的元素是不能修改只能查看的windows
# 元组
tuple = (1,2,3)
复制代码
集合:相似数学中的集合,每一个集合中的元素是无序的,不能够有重复的对象,所以能够经过集合把重复的数据去除!浏览器
# 集合
list = [1,1,2,2,3,4,5]
set = set(list)
# result {1,2,3,4,5}
复制代码
# 打开文件
open(name,[, mode[,buffering]])
f = open('/Users/GreetingText/PycharmProjects/demo/hello.txt')
# 读写文件
f = open('/Users/GreetingText/PycharmProjects/demo/hello.txt', 'w')
f.write('Hello World')
f = open('/Users/GreetingText/PycharmProjects/demo/hello.txt', 'r')
content = f.read()
print(content)
# result Hello World
# 关闭文件
f.close()
复制代码
Mac 系统自带Python 2.7,安装 新版本请前往官网下载,安装成功以后,在命令行输入python3 如图:bash
推荐PyCharm数据结构
安装Scrapy并建立项目scrapy
pip install scrapy
scrapy startproject QuickDemo
cd QuickDemo
复制代码
具体代码(须要事先安装BeautifulSoup库)ide
# -*- coding:utf-8 -*-
import scrapy
from bs4 import BeautifulSoup
class tsSpride(scrapy.Spider):
name = 'test' # 爬虫的惟一名字,在项目中爬虫名字必定不能重复
# start_requests() 必须返回一个迭代的Request
def start_requests(self):
# 待爬取的URL列表
urls = ['http://www.jianshu.com/',]
# 模拟浏览器
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
for url in urls:
yield scrapy.Request(url=url, headers=headers, callback=self.parse)
# 处理每一个请求的下载响应
def parse(self, response):
soup = BeautifulSoup(response.body, 'html.parser')
titles = soup.find_all('a', 'title')
for title in titles:
print(title.string)
try:
file = open(r'/Users/GreetingText/QuickDemo/jianshu.txt', 'w')
# 将爬取到的文章题目写入txt中
for title in titles:
file.write(title.string + '\n')
finally:
if file:
# 关闭文件(很重要)
file.close()
复制代码
scrapy crawl test
复制代码
本文参考文章ui