【问题标题】:Cannot find the attribute in HTML source but the Python program runs correctly在 HTML 源代码中找不到该属性,但 Python 程序运行正常
【发布时间】:2020-01-17 07:46:23
【问题描述】:

我正在抓取一个 YouTube 页面并在网上找到一个开放的程序代码。代码运行并返回正确的结果。但是,当我逐句学习代码时,我发现我在源代码中找不到该属性。我在页面源代码中搜索它,检查元素视图并将原始代码复制并粘贴到 word 中。哪里都找不到。

这是怎么发生的?

代码如下:

soup=BeautifulSoup(result.text,"lxml")

# cannot find yt-lockup-meta-info anywhere......
view_element=soup.find_all("ul",class_="yt-lockup-meta-info")

totalview=0

for objects in view_element:
    view_list=obj.findChildren()
    for element in view_list:
        if element.string.endwith("views"):
            videoviews=element.text.replace("views","").replace(",","")
            totalview=totalview+int(videoviews)
            print(videoviews)

print("----------------------")

print("Total_Views"+str(totalview))

我搜索的属性是“yt-lockup-meta-info”。

页面来源为here

The original page.

【问题讨论】:

    标签: python html web-crawler


    【解决方案1】:

    我看到了一些问题,如果我看到完整的代码,我认为这些问题可能会得到解决。但是,在此块中需要解决一些问题。

    例如,这行应该是:

    for obj in view_element:
    

    代替:

    for objects in view_element:
    

    遍历“view_element”时,您只引用了一个“obj”,而不是多个对象。

    另外,如果有可以直接搜索的类,就不需要搜索“views”这个词了。

    以下是我将如何解决这个问题。希望这会有所帮助。

    #Go to website and convert page source to Soup
    response = requests.get('https://www.youtube.com/results?search_query=web+scraping+youtube')
    soup = BeautifulSoup(response.text, 'lxml')
    f.close()
    
    
    
    videos = soup.find_all('ytd-video-renderer') #Find all videos
    total_view_count = 0
    for video in videos:
        video_meta = video.find('div', {'id': 'metadata'}) #The text under the video title
        view_count_text = video_meta.find_all('span', {'class': 'ytd-video-meta-block'})[0].text.replace('views', '').strip() #The view counter
        #Converts view count to integer
        if 'K' in view_count_text:
            video_view_count = int(float(view_count_text.split('K')[0])*1000)
        elif 'M' in view_count_text:
            video_view_count = int(float(view_count_text.split('M')[0])*1000000)
        elif 'B' in view_count_text:
            video_view_count = int(float(view_count_text.split('B')[0])*1000000000)
        else:
            video_view_count = int(view_count_text)
        print(video_view_count)
        total_view_count += video_view_count
    
    
    
    print(total_view_count)
    

    【讨论】:

    • 谢谢卢克。但它没有解决问题。我的问题是,代码中有属性“yt-lockup-meta-info”,但我在页面源中找不到它。这是怎么发生的?谢谢。
    • 很可能,自从编写代码以来,该网站可能已经更新了它的标签和类。因此,您需要将属性名称更改为新的属性名称。这在网络抓取时偶尔会发生,这就是为什么您应该尽可能不使用唯一属性 ID。
    • 是的,我自己在 YouTube 上刮过很多次。简短的回答是对不同请求的不同响应。例如,您可以按照本教程 (support.google.com/youtube/thread/17725319?hl=en) 进行操作并恢复到 YouTube 的旧版式。如果您想将更多 cmets 加载到视频中,则必须单击“加载更多”按钮而不是无限滚动,并且正如您可以想象的那样,在检查时,您的 requests.text 中会出现不同的信息。
    猜你喜欢
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2018-08-08
    • 1970-01-01
    • 2017-04-07
    • 2019-12-22
    • 2017-11-11
    相关资源
    最近更新 更多