Python递归爬取今日头条指定用户一个月内发表的所有文章,视频,微头条

cha = (datetime.now() - datetime(int(result_time[0]), int(result_time[1]),

int(result_time[2]))).days

print(cha)

if 30 < cha <= 32:

print(‘完成’)

break_flag.append(1)

break

continue

if cha > 32:

print(‘完成’)

break_flag.append(1)

break

row = {‘发表时间’: article_time[0], ‘标题’: article_title[0].strip(‘"’),

‘来源’: article_source[0],‘所有图片’:article_image,

‘文章内容’: article_content.strip()}

with open(‘/toutiao/’ + str(csv_name) + ‘文章.csv’, ‘a’, newline=‘’, encoding=‘gb18030’)as f:

f_csv = csv.DictWriter(f, headers1)

f_csv.writeheader()

f_csv.writerow(row)

print(‘正在爬取文章:’, article_title[0].strip(‘"’), article_time[0],

‘https://www.toutiao.com/i’ + i[‘group_id’])

time.sleep(1)

else:

pass

except Exception as e:

print(e, ‘https://www.toutiao.com/i’ + i[‘group_id’])

wenzhang(url=url, max_behot_time=max_behot_time, csv_name=csv_name, n=n)

else:

pass

except KeyError:

n += 1

print(‘第’ + str(n) + ‘次请求’, first_url)

time.sleep(1)

if n == max_qingqiu:

print(‘请求超过最大次数’)

break_flag.append(1)

else:

pass

except Exception as e:

print(e)

else:

pass

print(max_behot_time)

print(data)

文章详情页数据(已合并到文章数据)

def get_wenzhang_detail(url, csv_name=0):

headers1 = [‘发表时间’, ‘标题’, ‘来源’, ‘文章内容’]

res = requests.get(url, headers=headers_a, cookies=cookies)

time.sleep(1)

article_title = re.findall(“title: ‘(.*?)’”, res.text)

article_content = re.findall(“content: ‘(.*?)’”, res.text, re.S)

pattern = re.compile(r"[(a-zA-Z~-_!@#$%^+*&\/?|:.<>{}()';=)*|\d]")

article_content = re.sub(pattern, ‘’, article_content[0])

article_time = re.findall(“time: ‘(.*?)’”, res.text)

article_source = re.findall(“source: ‘(.*?)’”, res.text, re.S)

result_time = []

[result_time.append(i) for i in str(article_time[0]).split(’ ‘)[0].replace(’-‘, ‘,’).split(’,')]

print(result_time)

cha = (datetime.now() - datetime(int(result_time[0]), int(result_time[1]), int(result_time[2]))).days

print(cha)

if cha > 8:

return None

row = {‘发表时间’: article_time[0], ‘标题’: article_title[0].strip(‘"’), ‘来源’: article_source[0],

‘文章内容’: article_content.strip()}

with open(‘/toutiao/’ + str(csv_name) + ‘文章.csv’, ‘a’, newline=‘’)as f:

f_csv = csv.DictWriter(f, headers1)

f_csv.writeheader()

f_csv.writerow(row)

print(‘正在爬取文章:’, article_title[0].strip(‘"’), article_time[0], url)

time.sleep(0.5)

return ‘ok’

视频数据

break_flag_video = []

def shipin(url, max_behot_time=0, csv_name=0, n=0):

max_qingqiu = 20

headers2 = [‘视频发表时间’, ‘标题’, ‘来源’, ‘视频链接’]

first_url = ‘https://www.toutiao.com/c/user/article/?page_type=0&user_id=%s&max_behot_time=%s&count=20&as=%s&cp=%s&_signature=%s’ % (

url.split(‘/’)[-2], max_behot_time, get_as_cp()[‘as’], get_as_cp()[‘cp’],

get_signature(url.split(‘/’)[-2], max_behot_time))

while n < max_qingqiu and not break_flag_video:

try:

res = requests.get(first_url, headers=headers_a, cookies=cookies)

data = json.loads(res.text)

print(data)

max_behot_time = data[‘next’][‘max_behot_time’]

if max_behot_time:

video_list = data[‘data’]

for i in video_list:

try:

start_time = i[‘behot_time’]

video_title = i[‘title’]

video_source = i[‘source’]

detail_url = ‘https://www.ixigua.com/i’ + i[‘item_id’]

resp = requests.get(detail_url, headers=headers())

r = str(random.random())[2:]

url_part = “/video/urls/v/1/toutiao/mp4/{}?r={}”.format(

re.findall(‘“video_id”:“(.*?)”’, resp.text)[0], r)

s = crc32(url_part.encode())

api_url = “https://ib.365yg.com{}&s={}”.format(url_part, s)

resp = requests.get(api_url, headers=headers())

j_resp = resp.json()

video_url = j_resp[‘data’][‘video_list’][‘video_1’][‘main_url’]

video_url = b64decode(video_url.encode()).decode()

print((int(str(time.time()).split(‘.’)[0])-start_time)/86400)

if 30 < (int(str(time.time()).split(‘.’)[0]) - start_time) / 86400 <= 32:

print(‘完成’)

break_flag_video.append(1)

continue

if (int(str(time.time()).split(‘.’)[0]) - start_time) / 86400 > 32:

print(‘完成’)

break_flag_video.append(1)

break

row = {‘视频发表时间’: time.strftime(‘%Y-%m-%d %H:%M:%S’, time.localtime(start_time)),

‘标题’: video_title, ‘来源’: video_source,

‘视频链接’: video_url}

with open(‘/toutiao/’ + str(csv_name) + ‘视频.csv’, ‘a’, newline=‘’, encoding=‘gb18030’)as f:

f_csv = csv.DictWriter(f, headers2)

f_csv.writeheader()

f_csv.writerow(row)

print(‘正在爬取视频:’, video_title, detail_url, video_url)

time.sleep(3)

except Exception as e:

print(e, ‘https://www.ixigua.com/i’ + i[‘item_id’])

shipin(url=url, max_behot_time=max_behot_time, csv_name=csv_name, n=n)

except KeyError:

n += 1

print(‘第’ + str(n) + ‘次请求’, first_url)

time.sleep(3)

if n == max_qingqiu:

print(‘请求超过最大次数’)

break_flag_video.append(1)

except Exception as e:

print(e)

else:

pass

微头条

break_flag_weitoutiao = []

def weitoutiao(url, max_behot_time=0, n=0, csv_name=0):

max_qingqiu = 20

headers3 = [‘微头条发表时间’, ‘来源’, ‘标题’, ‘文章内图片’, ‘微头条内容’]

while n < max_qingqiu and not break_flag_weitoutiao:

try:

first_url = ‘https://www.toutiao.com/api/pc/feed/?category=pc_profile_ugc&utm_source=toutiao&visit_user_id=%s&max_behot_time=%s’ % (

url.split(‘/’)[-2], max_behot_time)

print(first_url)

res = requests.get(first_url, headers=headers_a, cookies=cookies)

data = json.loads(res.text)

print(data)

max_behot_time = data[‘next’][‘max_behot_time’]

weitoutiao_list = data[‘data’]

for i in weitoutiao_list:

try:

detail_url = ‘https://www.toutiao.com/a’ + str(i[‘concern_talk_cell’][‘id’])

print(detail_url)

resp = requests.get(detail_url, headers=headers(), cookies=cookies)

start_time = re.findall(“time: ‘(.*?)’”, resp.text, re.S)

weitoutiao_name = re.findall(“name: ‘(.*?)’”, resp.text, re.S)

weitoutiao_title = re.findall(“title: ‘(.*?)’”, resp.text, re.S)

weitoutiao_images = re.findall(‘images: [“(.*?)”]’,resp.text,re.S)

print(weitoutiao_images)

if weitoutiao_images:

weitoutiao_image = ‘http:’ + weitoutiao_images[0].replace(‘u002F’,‘/’).replace(‘\’,‘’)

print(weitoutiao_image)

else:

weitoutiao_image = ‘此头条内无附件图片’

weitoutiao_content = re.findall(“content: ‘(.*?)’”, resp.text, re.S)

result_time = []

[result_time.append(i) for i in str(start_time[0]).split(’ ‘)[0].replace(’-‘, ‘,’).split(’,')]

print(result_time)

cha = (

datetime.now() - datetime(int(result_time[0]), int(result_time[1]), int(result_time[2]))).days

print(cha)

if cha > 30:

break_flag_weitoutiao.append(1)

print(‘完成’)

break

row = {‘微头条发表时间’: start_time[0], ‘来源’: weitoutiao_name[0],

‘标题’: weitoutiao_title[0].strip(‘"’),‘文章内图片’: weitoutiao_image,

‘微头条内容’: weitoutiao_content[0].strip(‘"’)}

with open(‘/toutiao/’ + str(csv_name) + ‘微头条.csv’, ‘a’, newline=‘’, encoding=‘gb18030’)as f:

f_csv = csv.DictWriter(f, headers3)

f_csv.writeheader()

f_csv.writerow(row)

time.sleep(1)

print(‘正在爬取微头条’, weitoutiao_name[0], start_time[0], detail_url)

except Exception as e:

print(e, ‘https://www.toutiao.com/a’ + str(i[‘concern_talk_cell’][‘id’]))

weitoutiao(url=url, max_behot_time=max_behot_time, csv_name=csv_name, n=n)

except KeyError:

n += 1

print(‘第’ + str(n) + ‘次请求’)

time.sleep(2)

if n == max_qingqiu:

print(‘请求超过最大次数’)

break_flag_weitoutiao.append(1)

else:

pass

except Exception as e:

print(e)

else:

pass

获取需要爬取的网站数据

def csv_read(path):

data = []

with open(path, ‘r’, encoding=‘gb18030’) as f:

reader = csv.reader(f, dialect=‘excel’)

for row in reader:

data.append(row)

return data

启动函数

def main():

for j, i in enumerate(csv_read(‘toutiao-suoyou.csv’)):

data_url = data.get_nowait()

if ‘文章’ in i[3]:

启动抓取文章函数

print(‘当前正在抓取文章第’, j, i[2])

headers1 = [‘发表时间’, ‘标题’, ‘来源’, ‘所有图片’, ‘文章内容’]

with open(‘/toutiao/’ + i[0] + ‘文章.csv’, ‘a’, newline=‘’)as f:

f_csv = csv.DictWriter(f, headers1)

f_csv.writeheader()

break_flag.clear()

wenzhang(url=i[2], csv_name=i[0])

if ‘视频’ in i[3]:

启动爬取视频的函数

print(‘当前正在抓取视频第’, j, i[2])

headers2 = [‘视频发表时间’, ‘标题’, ‘来源’, ‘视频链接’]

with open(‘/toutiao/’ + i[0] + ‘视频.csv’, ‘a’, newline=‘’)as f:

f_csv = csv.DictWriter(f, headers2)

f_csv.writeheader()

break_flag_video.clear()

shipin(url=i[2], csv_name=i[0])

if ‘微头条’ in i[3]:

启动获取微头条的函数

headers3 = [‘微头条发表时间’, ‘来源’, ‘标题’, ‘文章内图片’, ‘微头条内容’]

print(‘当前正在抓取微头条第’, j, i[2])

with open(‘/toutiao/’ + i[0] + ‘微头条.csv’, ‘a’, newline=‘’)as f:

f_csv = csv.DictWriter(f, headers3)

f_csv.writeheader()

break_flag_weitoutiao.clear()

weitoutiao(url=i[2], csv_name=i[0])

多线程启用

def get_all(urlQueue):

while True:

try:

不阻塞的读取队列数据

data_url = urlQueue.get_nowait()

i = urlQueue.qsize()

except Exception as e:

break

print(data_url)

if ‘文章’ in data_url[3]:

文末有福利领取哦~

👉一、Python所有方向的学习路线

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。img

👉二、Python必备开发工具

img
👉三、Python视频合集

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
img

👉 四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。(文末领读者福利)
img

👉五、Python练习题

检查学习结果。
img

👉六、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
img

img

👉因篇幅有限,仅展示部分资料,这份完整版的Python全套学习资料已经上传

小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Python爬虫全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注:python)
img

img

img

👉因篇幅有限,仅展示部分资料,这份完整版的Python全套学习资料已经上传

小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Python爬虫全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注:python)
[外链图片转存中…(img-tdzJZOzz-1710879227724)]

  • 11
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
今日头条爬虫技术说明 ========== 整体思路 -------- 1. 抓取今日头条app的数据包 2. 分析数据包,找出请求的数据(如文章列表,文章url等) 3. 根据文章url等信息,抓取文章内容 4. 若文章中包含视频,则取视频url,然后下载 具体实现 ------ ### 一、抓包 ### 1. 工具:`Fiddler`、 `android`手机、`google浏览器` 2. 步骤: (1)本示例采用[Fiddler](http://fiddler2.com/ "Fiddler")来抓包,安装到电脑,我的电脑是win10 (2)具体配置及使用请见[http://jingyan.baidu.com/article/03b2f78c7b6bb05ea237aed2.html](http://jingyan.baidu.com/article/03b2f78c7b6bb05ea237aed2.html "百度经验") (3)打开今日头条app,开始抓包,抓取到的包如下:![](http://i.imgur.com/fC3y96p.png) (4)经分析得知左侧的json文件及为文章列表,如图![](http://i.imgur.com/I2Z8Iph.png) 如右侧第一个content所指的json文件,文件内容为![](http://i.imgur.com/lwaDLHP.png)此时手机上的信息为 <img src = "http://i.imgur.com/LFSL1AA.png" width = "40%"> 可得上面的结论正确 ### 二、分析 ### 1. 分析所抓到的文章列表数据包:大致分为两类,一类是有视频文章,一类则是没有视频文章。 有视频文章json内容里均有`video_id`这个key,如下图所示:![](http://i.imgur.com/T4hqaIc.png) 2. 没有视频文章:json文件内容均包含`title`、 `abstract`、 `article_url`等信息,具体内容如下. -------- 该资源内项目源码是个人的毕设,代码都测试ok,都是运行成功后才上传资源,答辩评审平均分达到96分,放心下载使用! <项目介绍> 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。 --------
使用 Scrapy 爬取今日头条可以分为以下步骤: 1. 创建 Scrapy 项目 ``` scrapy startproject toutiao ``` 2. 创建一个 Spider 在 Scrapy 项目中,每个爬虫都是由一个 Spider 类来定义的。在 `spiders` 文件夹下创建一个 `toutiao_spider.py` 文件,并编写以下代码: ```python import scrapy class ToutiaoSpider(scrapy.Spider): name = "toutiao" start_urls = [ 'https://www.toutiao.com/ch/news_hot/', ] def parse(self, response): for article in response.css('div.card'): yield { 'title': article.css('div.title-box a::text').get(), 'url': article.css('div.title-box a::attr(href)').get(), 'source': article.css('a.lbtn.source::text').get(), 'time': article.css('span.time::text').get(), } next_page = response.css('a.next::attr(href)').get() if next_page is not None: yield response.follow(next_page, self.parse) ``` 在 Spider 中,我们首先指定了 Spider 的名称和起始 URL,然后定义了一个 `parse` 方法,用于解析响应并提取数据。在这个例子中,我们使用 CSS 选择器来提取文章的标题、URL、来源和发布时间,并将其作为字典类型的 item 返回。最后,我们通过在响应中查找“下一页”的链接来实现翻页,并使用 `response.follow` 方法来跟踪这些链接,最终递归调用 `parse` 方法。 3. 运行 Spider 完成 Spider 的编写后,我们可以在命令行中运行以下命令来启动爬虫: ``` scrapy crawl toutiao -o articles.csv ``` 此命令将运行名为 `toutiao` 的 Spider,并将结果输出到 `articles.csv` 文件中。您可以将此文件用于进一步的数据分析和处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值