<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          python獲取阿里巴巴國際站商家信息

          共 8594字,需瀏覽 18分鐘

           ·

          2022-01-04 19:51

          幫一個(gè)做外貿(mào)的朋友搞的,他需要電話號(hào)去和商家溝通,提供國際貨運(yùn)一條龍服務(wù),不停地切換頁面查看手機(jī)號(hào),比較麻煩,幫他寫個(gè)腳本,一次性獲取下來,存成Excel。現(xiàn)在分享一下過程,同時(shí)記錄一下他欠我一頓飯。


          前言

          阿里巴巴國際站上的商家號(hào)碼在不同的商家頁面上,如圖所示,需要登錄授權(quán)才能查看。

          本來想直接通過接口去獲取,但是發(fā)現(xiàn)每次請求都有一個(gè)動(dòng)態(tài)的spm參數(shù)不同的變動(dòng),所以決定簡單一點(diǎn)用selenium啟一個(gè)webdriver,效率比較慢。

          1.啟動(dòng)webdriver,并完成登錄

          from selenium.webdriver import ChromeOptionsfrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWaitimport reimport timefrom lxml import etreeimport csv

          # 完成登錄 登陸class Chrome_drive(): def __init__(self):
          option = ChromeOptions() option.add_experimental_option('excludeSwitches', ['enable-automation']) option.add_experimental_option('useAutomationExtension', False) NoImage = {"profile.managed_default_content_settings.images": 2} # 控制 沒有圖片 option.add_experimental_option("prefs", NoImage) # option.add_argument(f'user-agent={ua.chrome}') # 增加瀏覽器頭部 # chrome_options.add_argument(f"--proxy-server=http://{self.ip}") # 增加IP地址。。 # option.add_argument('--headless') #無頭模式 不彈出瀏覽器 self.browser = webdriver.Chrome(executable_path="./chromedriver", options=option) self.browser.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', { 'source': 'Object.defineProperty(navigator,"webdriver",{get:()=>undefined})' }) #去掉selenium的驅(qū)動(dòng)設(shè)置
          self.browser.set_window_size(1200,768) self.wait = WebDriverWait(self.browser, 12)
          def get_login(self): url='https://passport.alibaba.com/icbu_login.htm'
          self.browser.get(url) #self.browser.maximize_window() # 在這里登陸的中國大陸的郵編 #這里進(jìn)行人工登陸。 k = input("輸入1") if 'Your Alibaba.com account is temporarily unavailable' in self.browser.page_source: self.browser.close() while k == 1: break self.browser.refresh() # 刷新方法 refres return

          為了快速加載web頁面,瀏覽器設(shè)置不加載圖片,打開登錄頁后死循環(huán)等待,手動(dòng)登錄完成后,控制臺(tái)輸入1 跳出循環(huán)。

          2.獲取頁面內(nèi)容

          分析網(wǎng)頁

          我們首先獲取頁面上class=item-main的dom,可以拿到商家信息,然后獲取dom下class=cd的a標(biāo)簽的src屬性可以獲取商家詳細(xì)信息頁面鏈接,獲取信息后存成csv文件。代碼實(shí)現(xiàn)如下:

          #獲取判斷網(wǎng)頁文本的內(nèi)容:    def index_page(self,page,wd):        """        抓取索引頁        :param page: 頁碼        """        print('正在爬取第', page, '頁')
          url = f'https://www.alibaba.com/trade/search?page={page}&keyword={wd}&f1=y&indexArea=company_en&viewType=L&n=38' js1 = f" window.open('{url}')" # 執(zhí)行打開新的標(biāo)簽頁 print(url) self.browser.execute_script(js1) # 打開新的網(wǎng)頁標(biāo)簽 # 執(zhí)行打開新一個(gè)標(biāo)簽頁。 self.browser.switch_to.window(self.browser.window_handles[-1]) # 此行代碼用來定位當(dāng)前頁面窗口 self.buffer() # 網(wǎng)頁滑動(dòng) 成功切換 #等待元素加載出來 time.sleep(3)
          self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#J-items-content'))) #獲取網(wǎng)頁的源代碼 html = self.browser.page_source
          self.get_products(wd,html)
          self.close_window()
          def get_products(self, wd, html_text): """ 提取商品數(shù)據(jù) """ e = etree.HTML(html_text) item_main = e.xpath('//div[@id="J-items-content"]//div[@class="item-main"]') items = e.xpath('//div[@id="J-items-content"]//div[@class="item-main"]') print('公司數(shù) ', len(items)) for li in items: company_name = ''.join(li.xpath('./div[@class="top"]//h2[@class="title ellipsis"]/a/text()')) # 公司名稱 company_phone_page = ''.join(li.xpath('./div[@class="top"]//a[@class="cd"]/@href')) # 公司電話連接 product = ''.join(li.xpath('.//div[@class="value ellipsis ph"]/text()')) # 主要產(chǎn)品 Attrs = li.xpath('.//div[@class="attrs"]//span[@class="ellipsis search"]/text()') length = len(Attrs) counctry = '' total_evenue = '' sell_adress = '' product_img = '' if length > 0: counctry = ''.join(Attrs[0]) # 國家 if length > 1: total_evenue = ''.join(Attrs[1]) # Total 收入 if length > 2: sell_adress = ''.join(Attrs[2]) # 主要銷售地 if length > 3: sell_adress += '、' + ''.join(Attrs[3]) # 主要銷售地 if length > 4: sell_adress += '、' + ''.join(Attrs[4]) # 主要銷售地 product_img_list = li.xpath('.//div[@class="product"]/div/a/img/@src') if len(product_img_list) > 0: product_img = ','.join(product_img_list) # 產(chǎn)品圖片 self.browser.get(company_phone_page) phone = '' address = '' mobilePhone = '' try: if 'Your Alibaba.com account is temporarily unavailable' in self.browser.page_source: self.browser.close() self.browser.find_element_by_xpath('//div[@class="sens-mask"]/a').click() phone = ''.join(re.findall('Telephone:(.*?)', self.browser.page_source, re.S)) mobilePhone = ''.join(re.findall('Mobile Phone:(.*?)', self.browser.page_source, re.S)) address = ''.join(re.findall('Address:(.*?)', self.browser.page_source, re.S)) except: print("該公司沒有電話") all_down = [wd, company_name, company_phone_page, product, counctry, phone, mobilePhone, address, total_evenue, sell_adress, product_img] save_csv(all_down) print(company_name, company_phone_page, product, counctry, phone, mobilePhone, address, total_evenue, sell_adress, product_img)

          注意:國際站列表圖片是懶加載的,也就是說沒有滑動(dòng)出來的時(shí)候產(chǎn)品圖片地址是空的,我們增加一個(gè)窗口滑動(dòng)操作和一個(gè)關(guān)閉標(biāo)簽頁的動(dòng)作

            def buffer(self): #滑動(dòng)網(wǎng)頁的        for i in range(33):            time.sleep(0.5)            self.browser.execute_script('window.scrollBy(0,380)', '')  # 向下滑行300像素。
          def close_window(self): length=self.browser.window_handles if len(length) > 3: self.browser.switch_to.window(self.browser.window_handles[1]) self.browser.close() time.sleep(1) self.browser.switch_to.window(self.browser.window_handles[-1])

          獲取信息如下
          然后是main方法,這里我省事了,就是先搜了一下關(guān)鍵詞之后,看了下一共多少頁,寫了個(gè)for循環(huán),有時(shí)間可以修改成獲取列表的總頁數(shù),自動(dòng)循環(huán):

          def save_csv(lise_line):    file = csv.writer(open("./alibaba_com_img.csv", 'a', newline="", encoding="utf-8"))    file.writerow(lise_line)
          def main(): """ 遍歷每一頁 """ run = Chrome_drive() run.get_login() #先登錄 wd ='henan' for i in range(1,32): run.index_page(i, wd)
          if __name__ == '__main__': csv_title = 'wd,company_name,company_phone_page,product,counctry,phone,mobilePhone,address,total_evenue,sell_adress,product_img'.split( ',') save_csv(csv_title) main()

          3.獲取產(chǎn)品圖片

          第二步執(zhí)行完,我們就獲取關(guān)鍵詞搜索后的全部商家信息,這一步我們把商家的產(chǎn)品圖片全部下載下來,代碼如下:

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

          import requestsimport pandas as pddef open_requests(img, img_name): img_url ='https:'+ img res=requests.get(img_url) with open(f"./downloads_picture/{img_name}", 'wb') as fn: fn.write(res.content)
          df1=pd.read_csv('./alibaba_com_img.csv',)for imgs in df1["product_img"]: imgList = str(imgs).split(',') if len(imgList) > 0: img = imgList[0] img_name = img[24:] print(img, img_name) open_requests(img, img_name)

          4.獲取插入圖片

          剛才保存的是一個(gè)csv文件,我們把csv轉(zhuǎn)成Excel,注意csv轉(zhuǎn)成Excel時(shí)不要直接用文件轉(zhuǎn)換,容易有亂碼問題,我們選擇數(shù)據(jù)導(dǎo)入方式轉(zhuǎn)換。
          選擇菜單欄選擇文件,然后選擇導(dǎo)入,菜單選擇csv文件然后點(diǎn)導(dǎo)入

          選擇文件原始格式:UTF-8,然后點(diǎn)下一步

          間隔符選擇逗號(hào)和制表符。

          把列數(shù)據(jù)格式全部輸入成文本,不然電話號(hào)會(huì)自動(dòng)轉(zhuǎn)成16進(jìn)制。。

          導(dǎo)入成功后,我們選擇C列然后插入一列,準(zhǔn)備插入圖片。

          插入第三步下載好的圖片,代碼如下:

          # -*- coding: utf-8 -*-
          from PIL import Imageimport osimport xlwings as xwpath='alibaba_com.xlsx'app = xw.App(visible=True, add_book=False)wb = app.books.open(path)
          sht = wb.sheets['Sheet1']img_list=sht.range("L2").expand('down').valueprint(len(img_list))

          def write_pic(cell,img_name): path=f'./downloads_picture/{img_name}' print(path) fileName = os.path.join(os.getcwd(), path) img = Image.open(path).convert("RGB") print(img.size) w, h = img.size x_s = 70 # 設(shè)置寬 excel中,我設(shè)置了200x200的格式 y_s = h * x_s / w # 等比例設(shè)置高 sht.pictures.add(fileName, left=sht.range(cell).left, top=sht.range(cell).top, width=x_s, height=y_s)

          if __name__ == '__main__':
          for index,imgs in enumerate(img_list): cell="C"+str(index + 2) imgsList = str(imgs).split(',') if len(imgsList) > 0: img = imgsList[0] img_name = img[24:] try: write_pic(cell,img_name) print(cell,img_name) except: print("沒有找到這個(gè)img_name的圖片",img_name)
          wb.save() wb.close() app.quit()

          最終效果如下:
          原文鏈接:https://blog.csdn.net/weixin_46602773/article/details/110849483

          文章轉(zhuǎn)載:Python編程學(xué)習(xí)圈
          (版權(quán)歸原作者所有,侵刪)

          點(diǎn)擊下方“閱讀原文”查看更多

          瀏覽 143
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  家庭乱伦第1页 | 激情国产内射 | 天堂久草| 18禁黄无码一区二区免费网站 | 老司机免费视频 |