丁香园论坛:http://www.dxy.cn/bbs/thread/626626#626626
import time
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
def login(browser, username, password):
try:
browser.find_element_by_link_text("登录").click()
browser.find_element_by_class_name("ico_pc").click()
element = browser.find_element_by_name("username")
element.clear()
element.send_keys(username)
element = browser.find_element_by_name("password")
element.clear()
element.send_keys(password)
browser.find_element_by_class_name("button").click()
except TimeoutException:
print("time out")
except NoSuchElementException:
print("No Element")
def get_content(browser):
print("success login")
time.sleep(5)
auth = browser.find_elements_by_class_name('auth') # 昵称
level = browser.find_elements_by_class_name('info') # 等级
user_atten = browser.find_elements_by_class_name('user_atten') # 用户属性
content = browser.find_elements_by_class_name('postbody') # 内容
sfile = open('data.txt','a',encoding='utf-8')
for i in range(len(content)):
num = user_atten[i].find_elements_by_tag_name('a')
data = str({'num':i+1,'name':auth[i].text,'level':level[i].text,'score':num[0].text,'vote':num[2].text,'dingdang':num[4].text,'content':content[i].text.replace(" ", "").replace("\n", "")}) +"\n"
sfile.writelines(data)
print("success write")
sfile.close()
if __name__ == '__main__':
browser = webdriver.Chrome(executable_path = 'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe')
browser.get('http://www.dxy.cn/bbs/thread/626626#626626')
login(browser, 'xxxxxxname', 'pwd')
get_content(browser)
browser.quit()
···
网友评论