TED爬蟲
這是沙特2016夏天齋月時候?qū)懙牡谝粋€爬蟲TED_spider.py狰贯。寫文章復(fù)習(xí)一下。
用到的庫
抓取目標(biāo)網(wǎng)址:https://www.ted.com/talks
sqlite3 數(shù)據(jù)庫
BeautifulSoup 解析頁面
urllib.request 發(fā)起請求
得到網(wǎng)頁信息
urlopen得到網(wǎng)頁源碼:
def make_soup(url):
html=urlopen(url).read()
return BeautifulSoup(html,"lxml")#html to lxml
image.png
如上圖用瀏覽器觀察找到信息所在位置。
關(guān)鍵是用beautiful soup 精確選中你要提取的信息瀑构,需要對HTML和CSS的熟悉笨腥,對BS4的熟悉:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html:
def get_talks(url):
talks=make_soup(url).find("div","row row-sm-4up row-lg-6up row-skinny")# tag and class
talk_links= [BASE_URL+h4.a["href"] for h4 in talks.findAll("h4","h9 m5")]#List Comprehensions
#there is "posted rated" info on the index page
return talk_links
數(shù)據(jù)庫初始化
用數(shù)據(jù)庫對得到的信息進(jìn)行存儲,這里用的sqlite馒吴,需要對sql和數(shù)據(jù)庫的了解:
if os.path.exists("data/TED.db"):
conn=sqlite3.connect("data/TED.db")
cur=conn.cursor()
else:
#建立數(shù)據(jù)庫
conn=sqlite3.connect("data/TED.db")
#建立cursor
cur=conn.cursor()
cur.execute('''CREATE TABLE TED
(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
speaker CHAR,
talk_name CHAR,
talk_link TEXT,
watch_times INT,
place CHAR,
length CHAR,
month CHAR,
brief_description TEXT,
transcript TEXT,
similar_topics TEXT
);''')
conn.commit()
然后就是流程代碼扎运,對所有演講網(wǎng)頁進(jìn)行遍歷,抓取信息饮戳,存入數(shù)據(jù)庫豪治。
接下來可以對數(shù)據(jù)進(jìn)行一系列分析。
todo
- 提升速度扯罐,多進(jìn)程负拟。
- 了解scrapy
- 登錄和反反爬蟲