webdriver可针对符号AJAX和JS型网站,是一种万能爬取方法。
QQ空间通过用户下拉右端的滚动条来判断用户需求,当下拉到最下端浏览器会发送AJAX请求给服务器,从而加载拓展部分,如果不利用模拟下拉则只能看到第一页超文本。
cookies是服务器对用户身份的一种记录。如果不清楚可以百度cookies和会话。
cookies:
将cookeis放在请求头中,利用requests构造get请求即可,但是qq空间cookies有效期很短不建议用这种方法!!!
webdriver:
没有给出解析,需要爬取内容可自行拓展。
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import re
def log():
wd = webdriver.Chrome()
url = 'https://i.qq.com/'
wd = webdriver.Chrome()
password = ''#帐号
key = ''#密码
wd.get(url)
wait = WebDriverWait(wd,5) #显示等待最多5秒 超过报Timeout
wd.switch_to.frame('login_frame') #转入登录框架
time.sleep(1)
entry=wd.find_element_by_link_text('帐号密码登录')
entry.click()
username = wait.until(EC.presence_of_element_located((By.ID,'u')))
username.send_keys(password)
#key = wd.find_element_by_id('p')
key = wait.until(EC.presence_of_element_located((By.ID,'p')))
key.send_keys(key)
log_button = wd.find_element_by_class_name('login_button')
log_button.click()
wd.switch_to.default_content()
wait.until(EC.presence_of_element_located((By.ID,'top_tips_seat')))
for i in range(3): #滚动条下拉,获取前三页html
js = "var q=document.documentElement.scrollTop=100000"
wd.execute_script(js)
time.sleep(1)
html = wd.page_source
wd.close()
Str = re.compile( '',re.S)
result = re.findall(Str,html)
return result
def main():
for each in log():
print(each)
if __name__ == '__main__':
main()