【转】搜狗微信公众号文章反爬虫完美攻克

2017年11月27日 13:43:16


很简单,selenium + chromedriver,搜狗的部分直接在chrome模拟浏览器内部操作即可,而mp.weixin.qq.com则是腾讯的了,不反爬虫,用urllib requests等等即可。

需要扫码登陆,不扫码只能采取10页数据


[python] view plain copy
  1. from selenium import webdriver  

  2. import time  

  3. from bs4 import BeautifulSoup  

  4. import threading  

  5.   

  6. driver = webdriver.Chrome()  

  7. driver.get("http://weixin.sogou.com/")  

  8. driver.find_element_by_xpath('//*[@id="loginBtn"]').click()  

  9.   

  10. find = input("输入你想查找的关键词")  

  11. driver.find_element_by_xpath('//*[@id="query"]').send_keys("%s"%find)  

  12. driver.find_element_by_xpath('//*[@id="searchForm"]/div/input[3]').click()  

  13. time.sleep(2)  

  14.   

  15. url_list = []  

  16. while True:  

  17.     page_source = driver.page_source  

  18.     #print(page_source)  

  19.     bs_obj = BeautifulSoup(page_source,"html.parser")  

  20.     one_url_list = bs_obj.findAll("div",{"class":"txt-box"})  

  21.     for url in one_url_list:  

  22.         url_list.append(url.h3.a.attrs['href'])  

  23.         #print(url.h3.a.attrs['href'])  

  24.     next_page = "http://weixin.sogou.com/weixin" + bs_obj.find("a",{"id":"sogou_next"}).attrs['href']  

  25.     driver.get(next_page)  

  26.     time.sleep(1)  

  27.   

  28. def get_img(url,num,connect,cursor):  

  29.     response = requests.get(url,headers = header).content  

  30.     content = str(response,encoding = "utf-8")  

  31.     bs_obj = BeautifulSoup(content,"html.parser")  

  32.     img_list = bs_obj.findAll("img")  

  33.     count = 0  

  34.     for img in img_list:  

  35.         try:  

  36.             imgurl=get_total_url(img.attrs["data-src"])  

  37.             store_name = "%s"%url_num+"%s"%count  

  38.             path = r"C:\Users\Mr.Guo\Pictures\weixin"  

  39.             check_mkdir(path)  

  40.             urllib.request.urlretrieve(imgurl,r"C:\Users\Mr.Guo\Pictures\weixin\%s.jpeg" %store_name)  

  41.             insert_into_table(connect,cursor,store_name,html)  

  42.             count += 1  

  43.         except Exception as e:  

  44.             pass  

  45.   

  46. for url_num in range(len(url_list)):  

  47.         t = threading.Thread(target = get_img,args = (url_list[url_num],url_num,connect,cursor,))  

  48.         t.start()  

  49.       



原文链接:https://blog.csdn.net/mr_guo_lei/article/details/78643974