爬蟲:2. 元素定位

元素定位

requests返回的response是html格式悯蝉,我們需要把需要的數(shù)據(jù)提取出來托慨,那么就需要元素定位。常用的元素定位方式有xpath和css,如果你熟悉javascript蕉世,也可以使用pyquery狠轻。
相關(guān)的庫有l(wèi)xml,BeautifuleSoap(官方已經(jīng)將BeautifulSoup改名為bs4了)。相關(guān)的教程太多了向楼,這里為了完整性,舉一個xpath例子湖蜕,做個小總結(jié)昭抒。

例子是抓取美容下所有分類和具體項(xiàng)目的相關(guān)信息。

# -*- coding:utf-8 -*-

"""
File Name : 'Spider_soyoung'.py
Description:
Author: 'chengwei'
Date: '2016/4/22' '9:43'
"""
import sys
import requests
import json
import random
import redis
import logging
import pymssql
import copy
import datetime
import time
import json
from lxml import etree
import re

reload(sys)
sys.setdefaultencoding('utf8')

class Spider_plastics(object):
    def __init__(self):
        self.user_agents = ['Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20130406 Firefox/23.0',
                             'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0',
                             'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533+  (KHTML, like Gecko) Element Browser 5.0',
                             'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',
                             'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14',
                             'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25',
                             'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1468.0 Safari/537.36',
                             'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; TheWorld)',
                             'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
                             'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36'
                            ]
        self.root_url = 'http://plastics.517mr.com/'
        #log
        self.logfilename = self.__class__.__name__ + '.log'
        logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',
                        filename=self.logfilename, filemode='a')
        # SQL
        self.conn = pymssql.connect(host='99.48.58.23', user='sa', password='123456', database='meirong', charset="utf8")
        self.cur = self.conn.cursor(as_dict=True)

    def get_detail_url(self):
        user_agent = random.choice(self.user_agents)
        header_2 = {
                    "User-Agent": user_agent
                    }

        s = requests.Session()
        url_list = []
        html = s.get(self.root_url, headers=header_2)
        time.sleep(3)
        selector = etree.HTML(html.text)
        content_1 = selector.xpath('//*[@id="zxmr"]//div[starts-with(@class,"xm_list")]')
        content_2 = selector.xpath('//*[@id="pfmr"]//div[starts-with(@class,"xm_list")]')
        content_3 = selector.xpath('//*[@id="zsmr"]//div[starts-with(@class,"xm_list")]')
        content_4 = selector.xpath('//*[@id="jgmr"]//div[starts-with(@class,"xm_list")]')
        content_5 = selector.xpath('//*[@id="sssx"]//div[starts-with(@class,"xm_list")]')
        content_6 = selector.xpath('//*[@id="mfzz"]//div[starts-with(@class,"xm_list")]')
        content_7 = selector.xpath('//*[@id="myjc"]//div[starts-with(@class,"xm_list")]')
        content_8 = selector.xpath('//*[@id="zymr"]//div[starts-with(@class,"xm_list")]')
        content_9 = selector.xpath('//*[@id="sbxf"]//div[starts-with(@class,"xm_list")]')

        temp_list = [
            {'type': u'整形美容', 'content': content_1},
            {'type': u'皮膚美容', 'content': content_2},
            {'type': u'注射美容', 'content': content_3},
            {'type': u'激光美容', 'content': content_4},
            {'type': u'瘦身美容', 'content': content_5},
            {'type': u'毛發(fā)種植', 'content': content_6},
            {'type': u'美牙健齒', 'content': content_7},
            {'type': u'中醫(yī)美容', 'content': content_8},
            {'type': u'失敗修復(fù)', 'content': content_9}
            ]

        for item in temp_list:

            for element in item['content']:
                link = element.xpath('.//a/@href')
                i = 3
                for m in range(0, len(link)):
                    if m == 0:
                        continue
                    else:
                        item_dict = {}
                        item_dict['categories'] = item['type']
                        name = element.xpath('string(.)').replace(' ', '').replace('\t', '').strip().split('\n')
                        link = element.xpath('.//a/@href')
                        item_dict['location'] = name[0]
                        item_dict['project_classification'] = name[i]
                        item_dict['url'] = link[m]
                        i += 1
                        url_list.append(copy.deepcopy(item_dict))
                        time.sleep(0.1)
        s.close()
        return url_list

    def get_detail_info(self):
        user_agent = random.choice(self.user_agents)
        header_2 = {
                    "User-Agent": user_agent
                    }

        url_list = self.get_detail_url()
        s = requests.Session()
        n = 0
        for item in url_list:
            n += 1
            if n == 153:
                print "test"
            res = s.get(item['url'], headers=header_2)
            if res.status_code == 200:
                selector = etree.HTML(res.text)
                content = selector.xpath('//*[@id="catelist"]//div[@class = "diy_tr"]')
                content_2 = selector.xpath('//div[@class = "price"]/em')
            else:
                logging.error("%s:%d" %(item['url'], res.status_code))
                continue

            if len(content) != 0:
                for element in content:
                        info_1 = element.xpath('./span[@class = "w1 outer"]')[0].xpath('string(.)').strip().split('\n')[0]
                        info_2 = element.xpath('./span[@class = "w3 outer"]')[0].xpath('string(.)').strip()
                        info_3 = element.xpath('./span[@class = "w4 outer"]')[0].xpath('string(.)').strip()
                        info_4 = element.xpath('./span[@class = "w5 outer"]')[0].xpath('string(.)').strip()
                        info_5 = element.xpath('./span[@class = "w6 outer"]')
                        temp_dict = {}
                        temp_dict['categories'] = item['categories']
                        temp_dict['location'] = item['location']
                        temp_dict['project_classification'] = item['project_classification']
                        temp_dict['feature'] = info_1
                        temp_dict['apply_to'] = info_2
                        temp_dict['price'] = info_3
                        temp_dict['refresh_cycle'] = info_4
                        temp_dict['attention'] = len(info_5[0].xpath('.//div[@class = "c6"]/em[@class = "x"]'))
                        time.sleep(0.6)
                        try:
                            sql = "INSERT INTO kanghua (categories, location, project_classification, feature, " \
                                  "apply_to, price, refresh_cycle, attention) VALUES ('%s','%s','%s', '%s', '%s', " \
                                  "'%s','%s','%s')" %(temp_dict['categories'],temp_dict['location'],temp_dict['project_classification'],
                                                      temp_dict['feature'], temp_dict['apply_to'],temp_dict['price'], temp_dict['refresh_cycle'],
                                                      temp_dict['attention'])
                            self.cur.execute(sql)
                            self.conn.commit()
                        except:
                            logging.error(" 第一種布局 INSERT ERROR")
                continue
            if len(content_2) != 0:
                logging.info("another css:%s %s %s" %(item['categories'], item['location'], item['project_classification']))
                temp_dict = {}
                temp_dict['price'] = selector.xpath('//div[@class = "price"]/em')[0].xpath('string(.)')
                temp_dict['categories'] = item['categories']
                temp_dict['location'] = item['location']
                temp_dict['project_classification'] = item['project_classification']
                temp_dict['feature'] = ''
                temp_dict['apply_to'] = ''
                temp_dict['refresh_cycle'] = ''
                temp_dict['attention'] = ''
                time.sleep(0.6)
                try:
                    sql = "INSERT INTO kanghua (categories, location, project_classification, feature, " \
                          "apply_to, price, refresh_cycle, attention) VALUES ('%s','%s','%s', '%s', " \
                          "'%s', '%s','%s','%s')" %(temp_dict['categories'],temp_dict['location'],
                                                    temp_dict['project_classification'],temp_dict['feature'],
                                                    temp_dict['apply_to'],temp_dict['price'], temp_dict['refresh_cycle'],
                                                    temp_dict['attention'])
                    self.cur.execute(sql)
                    self.conn.commit()
                except:
                    logging.error("第二種布局 INSERT ERROR")
            else:
                logging.error("error:%s %s %s" %(item['categories'], item['location'], item['project_classification']))



test = Spider_plastics()
test.get_detail_info()


xpath說明:

  1. 基本語法可參考W3CSchool

  2. 獲取某個節(jié)點(diǎn)下的所有文本可以使用string(.)

element.xpath('string(.)')
  1. 常用的功能函數(shù)
    starts-with
//div[starts-with(@id,'res')]

contains和and(.代表當(dāng)前節(jié)點(diǎn)怕磨,..表示父節(jié)點(diǎn))

//span[contains(.,'_Test') and contains(.,'KPI')]
  1. charome插件XPather肠鲫,測試xpath的好工具
  2. beautifulSoap文檔
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末或粮,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子渣锦,更是在濱河造成了極大的恐慌氢哮,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,589評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件听盖,死亡現(xiàn)場離奇詭異皆看,居然都是意外死亡背零,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,615評論 3 396
  • 文/潘曉璐 我一進(jìn)店門毛雇,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人禾乘,你說我怎么就攤上這事始藕∥榕桑” “怎么了剩胁?”我有些...
    開封第一講書人閱讀 165,933評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長晾腔。 經(jīng)常有香客問我啊犬,道長,這世上最難降的妖魔是什么剔应? 我笑而不...
    開封第一講書人閱讀 58,976評論 1 295
  • 正文 為了忘掉前任峻贮,我火速辦了婚禮应闯,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘嚼黔。我一直安慰自己惜辑,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,999評論 6 393
  • 文/花漫 我一把揭開白布碎节。 她就那樣靜靜地躺著狮荔,像睡著了一般胎撇。 火紅的嫁衣襯著肌膚如雪殖氏。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,775評論 1 307
  • 那天爵憎,我揣著相機(jī)與錄音婚瓜,去河邊找鬼巴刻。 笑死,一個胖子當(dāng)著我的面吹牛沥寥,可吹牛的內(nèi)容都是我干的柠座。 我是一名探鬼主播,決...
    沈念sama閱讀 40,474評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼蒂阱,長吁一口氣:“原來是場噩夢啊……” “哼录煤!你這毒婦竟也來了荞胡?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,359評論 0 276
  • 序言:老撾萬榮一對情侶失蹤廊营,失蹤者是張志新(化名)和其女友劉穎露筒,沒想到半個月后敌卓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,854評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡瘪吏,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,007評論 3 338
  • 正文 我和宋清朗相戀三年蕾盯,在試婚紗的時候發(fā)現(xiàn)自己被綠了蓝丙。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,146評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖沧烈,靈堂內(nèi)的尸體忽然破棺而出像云,到底是詐尸還是另有隱情,我是刑警寧澤迅诬,帶...
    沈念sama閱讀 35,826評論 5 346
  • 正文 年R本政府宣布惩歉,位于F島的核電站,受9級特大地震影響俏蛮,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜争涌,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,484評論 3 331
  • 文/蒙蒙 一亮垫、第九天 我趴在偏房一處隱蔽的房頂上張望伟骨。 院中可真熱鬧,春花似錦害晦、人聲如沸壹瘟。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,029評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽政冻。三九已至线欲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間苦锨,已是汗流浹背舟舒。 一陣腳步聲響...
    開封第一講書人閱讀 33,153評論 1 272
  • 我被黑心中介騙來泰國打工嗜憔, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人夺鲜。 一個月前我還...
    沈念sama閱讀 48,420評論 3 373
  • 正文 我出身青樓谣旁,卻偏偏與公主長得像滋早,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子搁进,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,107評論 2 356

推薦閱讀更多精彩內(nèi)容

  • 在使用selenium webdriver進(jìn)行元素定位時昔头,通常使用findElement或findElements...
    不勤奮閱讀 1,580評論 1 3
  • 使用selenium進(jìn)行自動化時少不了對元素進(jìn)行定位饼问,但目前前端大多使用框架vue,angular等揭斧,很多元素并沒...
    菠了個蘿閱讀 9,515評論 1 5
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理莱革,服務(wù)發(fā)現(xiàn)峻堰,斷路器,智...
    卡卡羅2017閱讀 134,672評論 18 139
  • 祝:老公元宵節(jié)快樂盅视!想你捐名,兒子,想我們的家闹击!
    我就是我hxh閱讀 183評論 0 0
  • 我住的地方離公路只有五米不到的距離镶蹋,每天汽笛聲伴隨著我,入睡赏半,醒來贺归。有拖拉機(jī)的,摩托車的断箫,汽車的仲义。也聽見大媽們晨走...
    東條二十閱讀 300評論 0 0