除了之前跟大家讲述过的视频、音乐以及时事新闻,关于爬虫可以做的事情有很多很多,像论坛也是其中之一,应用最火的内容,之前给大家罗列的爬虫实际内容有很多,但是还是希望将每个实际内容都跟大家说一下。让大家在遇到这些问题时候,可以有个参考,因此,根据大家罗列的清单,给大家继续安排python怎么爬取论坛,一起来看下吧~
库:requests,re,selenium,time
具体步骤:
一、搜索贴吧
准备一个自己想要爬取的内容
二、显示贴吧首页的帖子
要提取发帖人的名字和帖子主题,选择用正则表达式来实现,具体代码如下:
titles = re.findall('三、查看某一个帖子
通过观察网页源码,可以用正则表达式匹配到这部分回复,然后对于这些回复,也要进行处理后再显示出来。
comment_list2 = re.findall('post_bubble_middle_inner">https://www.mshxw.com/skin/sinaskin/image/nopic.gif', ' ').replace('', ' ')具体源码如下:
import requests
import time
import re
from selenium import webdriver
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/"
"53.0.2785.89 Safari/537.36"
}
class TieBa:
def __init__(self, name, url):
self.name = name # 贴吧名
self.url = url # 贴吧首页的url
# 显示首页上的帖子作者和标题
def get_homepage(self):
print("ntttttt{}吧".format(self.name))
res = requests.get(self.url, headers=headers)
titles = re.findall('https://www.mshxw.com/skin/sinaskin/image/nopic.gif<', res.text)
comment_list = re.findall('content clearfix">https://www.mshxw.com/skin/sinaskin/image/nopic.gif', res.text, re.DOTALL)
if len(comment_list) == 0:
comment_list = re.findall('d_post_content j_d_post_content ">https://www.mshxw.com/skin/sinaskin/image/nopic.gif', res.text, re.DOTALL)
# 带回复框的单独考虑
comment_list2 = re.findall('post_bubble_middle_inner">https://www.mshxw.com/skin/sinaskin/image/nopic.gif', ' ')
if "', ' ').replace('', ' ')
num += 1
if "src" in comment: # 处理图片信息
src_list = re.findall('src="https://www.mshxw.com/skin/sinaskin/image/nopic.gif"', comment)
pattern_list = re.findall('()', comment)
for s, p in zip(src_list, pattern_list):
comment = comment.replace(p, ' ' + s)
if "href" in comment: # 处理表情信息
pattern_list = re.findall('()', comment)
for p in pattern_list:
comment = comment.replace(p, ' ').replace("", '')
print(comment)
while True:
x = int(input("n输入1查看下一页,输入0回到首页,输入-1退出程序:"))
if x == -1:
exit()
if x == 0:
self.get_homepage()
if x == 1:
next_page = re.findall('下一页', res.text)
if len(next_page)>0:
self.get_page("http://tieba.baidu.com" + next_page[0])
else:
print("已经是最后一页了!")
# 利用selenium模拟浏览器查找贴吧
def search():
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(chrome_options=chrome_options)
browser.get("https://tieba.baidu.com/")
name = input("请输入想要进入的贴吧名字:")
browser.find_element_by_xpath('//*[@id="wd1"]').send_keys(name)
browser.find_element_by_xpath('//*[@id="tb_header_search_form"]/span[1]/a').click()
url = browser.current_url
if "tieba.baidu.com/f?ie=utf-8" in url: # 搜索的贴吧存在
print("正在进入{}吧,请稍等...".format(name))
time.sleep(2)
t = TieBa(name, url)
t.get_homepage()
else:
print("没有找到{}吧n".format(name))
main()
def main():
x = int(input("输入1搜索进入贴吧,输入-1退出程序:"))
if x == 1:
search()
else:
exit()
if __name__ == '__main__':
main()好了,以上就是爬取论坛的内容了,如果大家遇到这种问题,可以来看下小编的这篇内容,很容易解决的哦~



