首页 AI Studio教育版 帖子详情
爬取《青春有你2》信息没有输出结果,求指教!
收藏
快速回复
AI Studio教育版 问答课程答疑 4029 27
爬取《青春有你2》信息没有输出结果,求指教!
收藏
快速回复
AI Studio教育版 问答课程答疑 4029 27

模仿老师的程序进行了《青春有你2》信息爬取,结果没有任何输出信息,请求大神指点!程序中只改过User-Agent部分

import json
import re
import requests
import datetime
from bs4 import BeautifulSoup
today  = datetime.date.today().strftime('%Y%m%d')
def crawl_wiki_data():
    """
        爬取百度百科中《青春有你2》中参赛选手信息,返回html
        """
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0'
        }
    url = 'https://baike.baidu.com/item/青春有你第二季'
    #URL是指统一资源定位符。统一资源定位符是对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示,是互联网上标准资源的地址。互联网上的每个文           件都有一个唯一的URL,它包含的信息指出文件的位置以及浏览器应该怎么处理它。

    try:
        repsonse = requests.get(url,headers=headers)
        print(response.status_code)
        #将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
        soup = BeautifulSoup(response.text,'lxml')
        #返回的是class为table-view log-set-param的





























                #籍贯
        star["zone"] = all_tds[1].text
        #星座
        star["constellation"] = all_tds[2].text
        #身高
        star["height"] = all_tds[3].text
        #体重
        star["weight"] = all_tds[4].text
        #花语,去除掉花语中的单引号或双引号
        flower_word = all_tds[5].text
        for c in flower_word:
            if c in error_list:
                flower_word = flower_word.replace(c,'')
        star["flower_word"] = flower_word
        #公司
        if not all_tds[6].find('a') is None:
            star["company"] = all_tds[6].find('a').text
        else:
            star["company"] = all_tds[6].text
        stars.append(star)
    json_data = json.loads(str(stars).replace("\'","\""))
    with open('work/' + today + '.json','w',encoding='UTF-8') as f:
        json.dump(json_data,f,ensure_ascii=False)  #以中文方式存储json
def crawl_pic_urls():
    '''
    爬取每个选手的百度百科图片,并保存
    '''
    # 读取选手的信息
    with open('work/'+ today + '.json', 'r', encoding='UTF-8') as file:
        json_array = json.loads(file.read())
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0'
        }
    for star in json_array:
        pic_urls = []
        name = star['name']
        link = star['link']
         #!!!请在以下完成对每个选手图片的爬取,将所有图片url存储在一个列表pic_urls中!!!
        response = requests.get(link, headers=headers)
        print(response.status_code)
        soup = BeautifulSoup(response.text, 'lxml')  # 获取每个选手百度百科的网页的html

        pic = soup.find('div', {'class': 'summary-pic'})  # 找到图片的信息
        img = pic.find('img')
        # print(img)
        pic_url = img['src']
        print(pic_url)
        pic_urls.append(pic_url)
        #!!!根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中!!!
        down_pic(name,pic_urls)
def down_pic(name,pic_urls):
    '''
        根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中,
        '''
    path = 'work/'+'pics/'+name+'/'
    # path_test = 'work/'+'pics/test'
    if not os.path.exists(path):
         os.makedirs(path)
    for i, pic_url in enumerate(pic_urls):
        try:
            pic = requests.get(pic_url, timeout=15)
            string = str(i + 1) + '.jpg'
            with open(path+string, 'wb') as f:
                f.write(pic.content)
                print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))
        except Exception as e:
            print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))
            print(e)
            continue
def show_pic_path(path):
    '''
        遍历所爬取的每张图片,并打印所有图片的绝对路径
        '''
    pic_num = 0
    for (dirpath,dirnames,filenames) in os.walk(path):
        for filename in filenames:
            pic_num += 1
            print("第%d张照片:%s" % (pic_num,os.path.join(dirpath,filename)))
    print("共爬取《青春有你2》选手的%d照片" % pic_num)

 

所有标签        tables = soup.find_all('table',{'class':'table-view log-set-param'})        crawl_table_title = "参赛学员"        #根据“参赛学员”这个title来区分要截取的代码        for table in tables:            #对当前“参赛学员”节点前面的标签和字符串进行查找            table_titles = table.find_previous('div').find_all('h3')            for title in table_titles:                if(crawl_table_title in title):                    return table    except Exception as e:        print(e)def parse_wiki_data(table_html):    '''        从百度百科返回的html中解析得到选手信息,以当前日期作为文件名,存JSON文件,保存到work目录下        '''    bs = BeautifulSoup(str(table_html),'lxml')    all_trs = bs.find_all('tr')    #'tr'来源于右键浏览器页面,点击审查元素,出现的网页代码中的HTML 标签。它包含一个或多个th或td元素    error_list = ['\'','\"']  #花语,去除掉花语中的单引号或双引号    stars = []    for tr in all_trs[1:]:  #去掉all_trs[0]中的姓名、国家等标题内容        all_tds = tr.find_all('td')        star = {}        #姓名        star["name"] = all_tds[0].text        #个人百度百科链接        star["link"] = 'https://baike.baidu.com' + all_tds[0].find('a').get('href')#姓名下面的元素
0
收藏
回复
全部评论(27)
时间顺序
JavaRoom
#22 回复于2021-12

嘿嘿嘿,我已经解决了

0
回复
A
AIHN2030
#23 回复于2021-12
JavaRoom #22
嘿嘿嘿,我已经解决了

分享下呗,

才打印了几张,遇到报错,走不下去了。

https://aistudio.baidu.com/bjcpu02/user/1007723/3241967/notebooks/3241967.ipynb

0
回复
JavaRoom
#24 回复于2021-12
AIHN2030 #21
小白同问。原网页有变化,没爬到任何信息,如何修改?

早就变动了,自己再琢磨下

0
回复
DeepGeGe
#25 回复于2021-12
AIHN2030 #21
小白同问。原网页有变化,没爬到任何信息,如何修改?

这个可能得去学一学爬虫的知识了,因为爬虫就是有方法无定法,网页变动了必须修改。授人以渔,给你个课程链接:https://www.icourse163.org/learn/BIT-1001870001?tid=1450316449

0
回复
A
AIHN2030
#27 回复于2021-12
JavaRoom #24
早就变动了,自己再琢磨下

前面的根据网页修改了,看jason文件,基础信息是爬回来了。

就是后面图片那里,下了几张,后报错,就不往下走了。

try except 那段是作业自带的,照理碰到报错会跳过继续往下啊。

链接: https://aistudio.baidu.com/aistudio/projectdetail/3269019?contributionType=1

0
回复
p
paddler
#30 回复于2022-01

(1)网页table标签页变了,def crawl_wiki_data():中的部分修改为      

        tables = soup.find_all('table',{'data-sort':'sortDisabled'}) 

(2)有些选手的百度百科格式也变了,我就将他们跳过了,def crawl_pic_urls():中的部分修改为       

        if len(bs.select('.summary-pic a')):
            pic_list_url = bs.select('.summary-pic a')[0].get('href')
            pic_list_url = 'https://baike.baidu.com' + pic_list_url
        else:
            continue

0
回复
大连之星snort
#31 回复于2022-02

可以到我的项目库里有更新。

0
回复
在@后输入用户全名并按空格结束,可艾特全站任一用户