本文将介绍青灯教育爬虫资料中的一个项目——Python关羽。该项目可用于爬取知乎话题的相关内容,并将数据保存至本地数据库中。
一、Python关羽介绍
Python关羽是基于Python语言编写的爬虫程序,可用于爬取知乎话题的相关内容。该程序的主要功能包括:
1. 爬取知乎话题的相关问题和回答数据;
2. 将爬取的数据保存至本地数据库中;
3. 提供查询功能,用户可通过指定关键词和时间范围来搜索特定话题的相关问题和回答数据。
二、Python关羽的运行环境
1. Python 3.x;
2. SQLite3 数据库;
3. Chrome浏览器(用于web自动化)。
三、Python关羽使用的技术
1. Requests模块:用于HTTP请求,发起网络请求;
2. BeautifulSoup模块:用于解析HTML文档,提取出需要的数据;
3. Selenium模块:用于模拟浏览器操作,实现web自动化;
4. SQLite3模块:用于操作SQLite3数据库;
5. 时间模块:用于处理时间格式。
四、Python关羽的实现流程
1. 准备工作:创建SQLite3数据库,安装必要的 Python 模块,配置 Chromedriver 及地址和话题ID等。
2. 爬取话题的相关问题和回答数据:使用 Requests 发起HTTP请求,获取网页源代码。再使用 BeautifulSoup 解析出需要的数据,以列表的形式保存到内存中。
3. 保存数据到数据库中:遍历列表,将数据插入到 SQLite3 数据库中。
4. 查询数据:使用SQLite3模块从数据库中查询需要的数据,并以表格的形式展示出来。
五、Python关羽的主要代码实现
以下是Python关羽的关键代码,注释中包含了相关的解释。
```python
# 爬取数据
def get_qa_list(browser, topic_id, page):
"""
使用浏览器模拟滚动操作,获取问题和回答数据
Args:
browser: webdriver.Chrome object
浏览器驱动对象
topic_id: str
话题的id
page: int
要访问的页面数
Returns:
qa_list: list
包含问题和回答数据的列表
"""
# 构造要访问的url,topic_id和page都需要更换,其中榜单类型数据需要相应更新
url = f'https://www.zhihu.com/topic/{str(topic_id)}/hot?page=' + str(page)
browser.get(url) # 访问url
# 执行JS代码,将浏览器滑动到底部,以保证所有数据都被加载出来
# 如果使用selenium中的element.scrollIntoView(),会出现以下错误:
# selenium.common.exceptions.JavascriptException: Message: javascript error: Failed to execute 'scrollTo' on 'Window': parameter 1 ('y') is not a finite number.
# 所以这里使用的是window.scrollTo(0,document.body.scrollHeight)
browser.execute_script("window.scrollTo(0,document.body.scrollHeight)")
time.sleep(5) # 等待数据加载出来
# 使用 BeautifulSoup 解析HTML文档
soup = BeautifulSoup(browser.page_source, 'html.parser')
# 使用正则表达式匹配问题和回答数据
qa_list = []
for item in soup.find_all('div', class_='Feed'):
try:
question = item.find('h2', class_='ContentItem-title').text.strip()
answer = item.find('div', class_='RichText').text.strip()
author = item.find('span', class_='UserLink AuthorInfo-name').text.strip()
create_time = item.find('div', class_='ContentItem-time').find_all('span')[1].text.strip()
if len(create_time.split(' ')) == 2:
create_time += ':00'
create_time = datetime.strptime(create_time, '%Y-%m-%d %H:%M:%S')
qa_list.append([question, answer, author, create_time])
except:
pass
return qa_list
# 保存数据到SQLite3数据库中
def save_qa_to_db(conn, cur, qa_list):
"""
将question和answer列表中的数据存储到数据库表qa中
Args:
conn: connection object
数据库连接对象
cur: cursor object
数据库游标对象
qa_list: list
包含问题和回答数据的列表
"""
for qa in qa_list:
question = qa[0]
answer = qa[1]
author = qa[2]
create_time = qa[3]
# 注意这里使用"?"作为占位符,能够自动转义,避免SQL注入漏洞
cur.execute("INSERT INTO qa (question, answer, author, create_time) VALUES (?, ?, ?, ?)", (question, answer, author, create_time))
conn.commit() # 提交事务
# 查询数据并展示在表格中
def query_qa(conn, start_date, end_date, keyword):
"""
查询question和answer表中符合条件的数据,按时间升序排列,打印到控制台
Args:
conn: connection object
数据库连接对象
start_date: str
开始日期,格式为%Y-%m-%d
end_date: str
截止日期,格式为%Y-%m-%d
keyword: str
关键词
"""
# 构造SQL语句,并执行查询操作
sql = f"SELECT * FROM qa WHERE create_time >= '{start_date}' AND create_time <= '{end_date}' AND question LIKE '%{keyword}%'"
cur = conn.cursor()
cur.execute(sql)
rows = cur.fetchall()
# 表格化输出
table = PrettyTable(['问题', '回答', '作者', '时间'])
table.align['回答'] = 'l'
table.padding_width = 1
for row in rows:
table.add_row(row[:4])
print(table)
```
六、结语
本文介绍了青灯教育爬虫资料中的一个项目——Python关羽的相关知识。该项目包括了Python爬虫、数据存储、数据查询等方面的技术。在实现过程中,我们还使用了Requests、BeautifulSoup、Selenium等模块,并介绍了SQLite3数据库的操作技巧。Python关羽项目为我们提供了一个简单、实用的爬虫程序,为我们学习和实践Python爬虫提供了一个很好的实例。 如果你喜欢我们三七知识分享网站的文章, 欢迎您分享或收藏知识分享网站文章 欢迎您到我们的网站逛逛喔!https://www.ynyuzhu.com/
发表评论 取消回复