爬虫学习笔记(四)

该博客介绍模拟登录丁香园并抓取论坛页面人员基本信息与回复帖子内容的方法。先利用Selenium登录网站,包括切换到账号密码表单登录、输入账号密码点击登录,登录成功后定位抓取内容位置,最后将抓取内容存入文件,还给出了相关参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

任务:
模拟登录丁香园,并抓取论坛页面所有的人员基本信息与回复帖子内容。

一 首先利用selenium登录网站

1.切换到账号密码表单登录,我采用了利用style将display值变为block,代码如下:

from selenium import webdriver
import time


browser = webdriver.Chrome()
# 此处请选择您的浏览器

js1 = 'document.querySelector("#j_loginTab1").style.display="none";'
# document​.query​Selector():方法返回文档中与指定选择器或选择器组匹配的第一个 html元素Element。 如果找不到匹配项,则返回null。

browser.execute_script(js1)
# 对于某些操作,API没有提供的,如下拉进度条等,可以直接模拟运行JavaScript,使用execute_script()方法。

time.sleep(1)
js2 = 'document.querySelector("#j_loginTab2").style.display="block";'
browser.execute_script(js2)

参考资料:
https://zhuanlan.zhihu.com/p/29435831
https://developer.mozilla.org/zh-CN/docs/Web/API/Document/querySelector

2.定位到账号,密码input位置并输入已注册好的帐号密码,点击登录,代码如下:

input_name = browser.find_element_by_name('username')
input_name.clear()
input_name.send_keys('********')
# 此处请填写您的丁香园账号

input_pass = browser.find_element_by_name('password')
input_pass.clear()
input_pass.send_keys('********')
# 此处请填写您的密码

browser.find_element_by_xpath('//*[@class="form__button"]/button').click()

3.登录成功后,我们开始抓取页面,利用xpath定位到抓取内容的位置

from lxml import etree


url = 'http://www.dxy.cn/bbs/thread/626626'
req = requests.get(url, headers = self.headers)
html = req.text
tree = etree.HTML(html)
user = tree.xpath('//div[@id="postcontainer"]//div[@class="auth"]/a/text()')
content = tree.xpath('//td[@class="postbody"]')

4.将抓取内容存入文件。

整体代码

参考资料:
https://blog.youkuaiyun.com/naonao77/article/details/88316754

# -*- coding:utf-8 -*-
import requests, json, re, random,time
from bs4 import BeautifulSoup
from selenium import webdriver
from lxml import etree

class getUrl(object):
	"""docstring for getUrl"""
	def __init__(self):
		self.headers={
            "Connection": "keep-alive",  
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "  
                          "(KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",  
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",  
            "Accept-Encoding": "gzip, deflate, sdch",  
            "Accept-Language": "zh-CN,zh;q=0.8"
        };

	def run(self):
		browser = webdriver.Chrome()
		browser.get('https://auth.dxy.cn/accounts/login?service=http://www.dxy.cn/bbs/index.html')
		time.sleep(1)
		#切换账号密码登录表单
		js1 = 'document.querySelector("#j_loginTab1").style.display="none";'
		browser.execute_script(js1)
		time.sleep(1)
		js2 = 'document.querySelector("#j_loginTab2").style.display="block";'
		browser.execute_script(js2)
		#输入账号密码
		input_name = browser.find_element_by_name('username')
		input_name.clear()
		input_name.send_keys('*********')
		input_pass = browser.find_element_by_name('password')
		input_pass.clear()
		input_pass.send_keys('*******')
		browser.find_element_by_xpath('//*[@class="form__button"]/button').click()
		#此步骤应该有验证码,先跳过
		time.sleep(10)
		cookie = browser.get_cookies()
		cookie_dict = {i['name']:i['value'] for i in cookie}
		#转到抓取页面
		browser.get("http://www.dxy.cn/bbs/thread/626626#626626"); 
		html = browser.page_source
		tree = etree.HTML(html)
		user = tree.xpath('//div[@id="postcontainer"]//div[@class="auth"]/a/text()')
		content = tree.xpath('//td[@class="postbody"]')
		for i in range(0,len(user)):
			result = user[i].strip()+":"+content[i].xpath('string(.)').strip()
			#写入文件
			dir_file = open("DXY_records.txt",'a', encoding="utf-8")
			dir_file.write(result+"\n")
			dir_file.write('*' * 80+"\n")
			dir_file.close()
		print('*' * 5 +"抓取结束"+'*' * 5)


if __name__ == '__main__':
	geturl = getUrl()
	geturl.run()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值