page = urllib2.urlopen(url)
contents = page.read()
#獲得了整個網頁的內容也就是源代碼
print(contents)
url代表網址,contents代表網址所對應的源代碼,urllib2是需要用到的包,以上三句代碼就能獲得網頁的整個源代碼
2 獲取網頁中想要的內容(先要獲得網頁源代碼,再分析網頁源代碼,找所對應的標簽,然后提取出標簽中的內容)
2.1 以豆瓣電影排名為例子
網址是http://movie.douban.com/top250?format=text,進入網址后就出現如下的圖

然后查看源碼,找到對應的內容:(直接按f12)
就得到下面這張圖:
然后划出重點
然后開始編寫代碼:
#coding:utf-8
'''''
@author: 徐松偉
'''
import urllib.request
import re
from bs4 import BeautifulSoup
from distutils.filelist import findall
page = urllib.request.urlopen('http://movie.douban.com/top250?format=text')
contents = page.read()
#print(contents)
soup = BeautifulSoup(contents,"html.parser")
print("豆瓣電影TOP250" + "\n" +" 影片名 評分 評價人數 鏈接 ")
for tag in soup.find_all('div', class_='info'):
# print tag
m_name = tag.find('span', class_='title').get_text()
m_rating_score = float(tag.find('span',class_='rating_num').get_text())
m_people = tag.find('div',class_="star")
m_span = m_people.findAll('span')
m_peoplecount = m_span[3].contents[0]
m_url=tag.find('a').get('href')
print( m_name+" " + str(m_rating_score) + " " + m_peoplecount + " " + m_url )
遇到的問題:
安裝相關的庫文件,會遇到反爬取 。就是說不能一直爬取 。代碼經過多次運行以后就會觸動該網站的反爬取。
現在python3.X以后urllib2和urllib合並了 所以導入的時候用 import urllib.request 有什么說的不對的地方請評論指出。