需要的庫:
selenium:自動化操作瀏覽器
beautifulsoup:提取數據
安裝方式:pip
需要注意的是:selenium需要安裝對應的瀏覽器的驅動:
Chrome
下載chrome的webdriver: http://chromedriver.storage.googleapis.com/index.html
Firefox
Firefox驅動下載地址為:https://github.com/mozilla/geckodriver/releases/
IE
IE瀏覽器驅動下載地址為:http://selenium-release.storage.googleapis.com/index.html
根據自己selenium版本下載對應版本的驅動即可
下載後:如果是windows賦值驅動到瀏覽器的安裝目錄即可
思路:通過selenium打開瀏覽器,在搜索框輸入景區,然後就可以看到一個彈出的下拉框,每頁有20個景區,一共有40多頁,就需要提取每頁的景區名稱和地址,然後點擊下一頁再繼續提取,最後保存到文件中:
開始:
打開jupyter:
第一步:導入需要的庫:
from bs4 import BeautifulSoup from selenium import webdriver import time import pandas as pd
第二步:通過selenium打開瀏覽器,搜索
driver = webdriver.Firefox() driver.maximize_window() driver.get("https://www.amap.com/") elem = driver.find_element_by_xpath('//*[@id="searchipt"]') elem.send_keys("景區") elem = driver.find_element_by_xpath('/html/body/section[1]/header/div[2]/div/i') elem.click()
第三步:通過beautifulsoup獲取網頁源代碼,並提取需要的內容,並通過selenium重複點擊下一頁,重複提取至字典中:
dict = {} dict2 = {} for i in range(47): print(i) soup = BeautifulSoup(driver.page_source) for na, ad in zip(soup.select(".poi-name"), soup.select(".poi-addr")): print(na.string) dict[''.join(na.string.split())] = ad.string elem = driver.find_element_by_xpath( "/html/body/div[1]/section/section/div[2]/span[1]/i") elem.click() time.sleep(10)
第四步:導入到pandas中,導出至文件或者剪貼板:
data=pd.DataFrame.from_dict(dict,orient='index') data.reset_index(inplace=True) data.columns=["名稱","地址"] data.to_clipboard() data
結果:
關鍵字: 瀏覽器 bs4 elem.click