Request爬取网站(seo.chinaz.com)百度权重的查询结果
生活随笔
收集整理的這篇文章主要介紹了
Request爬取网站(seo.chinaz.com)百度权重的查询结果
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一:腳本需求
利用Python3查詢網站權重并自動存儲在本地數據庫(Mysql數據庫)中,同時導出一份網站權重查詢結果的EXCEL表格
數據庫類型:MySql
數據庫表單名稱:website_weight
表單內容及表頭設置:表頭包含有id、main_url(即要查詢的網站)、website_weight(網站權重)
?
要查詢的網站:EXCEL表格
二:需求實現
一:利用openpyxl模塊解析excel文件,將查詢的網站讀取到一個列表中保存
# 解析excel文件,取出所有的url def get_urls(file_path):wb = load_workbook(file_path)sheet = wb.activeurls = []for cell in list(sheet.columns)[1]:if cell != sheet['B1']:urls.append(cell.value)return wb, urls二:分析請求發送,偽造請求,取得HTML頁面
# 偽造請求,取得html頁面 def get_html(url):# 定義http的請求Headerheaders = {} # random.randint(1,99) 為了生成1到99之間的隨機數,讓UserAgent變的不同。 headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537." + str(random.randint(1, 99))# Referer地址使用待查詢的網址headers['Referer'] = "http://seo.chinaz.com/" + url + "/"html = ''try:html = requests.get("http://seo.chinaz.com/" + url + "/", headers=headers, timeout=5).textexcept Exception:passreturn html三:分析HTML頁面,利用BeautifulSoup模塊提取數據
# 利用BeautifulSoup模塊從html頁面中提取數據 def get_data(html, url):if not html:return url, 0soup = bs(html, "lxml")p_tag = soup.select("p.ReLImgCenter")[0]src = p_tag.img.attrs["src"]regexp = re.compile(r'^http:.*?(\d).gif')br = regexp.findall(src)[0]return url, br四:數據庫連接配置,并獲取游標
# 連接數據庫 def get_connect():conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='root',db='seotest',charset="utf8")# 獲取游標對象cursor = conn.cursor()return conn, cursor五:主程序邏輯編寫
if __name__ == "__main__":#命令行執行腳本文件,獲取excel文件路徑file_path = sys.argv[1]#獲取URL列表和excle工作簿wb, urls = get_urls(file_path)#獲取數據庫連接和游標conn, cursor = get_connect()#獲取工作簿當前工作sheetsheet = wb.active#數據庫插入語句sql_insert = '''insert into website_weight(main_url, website_weight) values (%s, %s)'''for row, url in enumerate(urls):if not url: continuehtml = get_html(url)data = get_data(html, url)# 插入數據到數據庫 cursor.execute(sql_insert, data)# 插入數據到Excel表中cell = sheet.cell(row=row + 2, column=3)cell.value = data[1]# 終端打印插入的數據print(data)conn.commit()conn.close()wb.save(file_path)wb.close()# cmd命令:python3 F:\算法與結構\網站權重.py F:\website.xlsx三:腳本運行及其實現結果
CMD執行
數據庫:
excel文件寫入:
?
轉載于:https://www.cnblogs.com/li1992/p/9863056.html
總結
以上是生活随笔為你收集整理的Request爬取网站(seo.chinaz.com)百度权重的查询结果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 编译安装samba-4.85
- 下一篇: 面向对象类和对象