首页 > 解决方案 > BeautifulSoup 循环无法捕获内容

问题描述

我的 BeautifulSoup 刮板循环遍历 URL 列表并根据需要捕获我的标准之一('month_year')。但是第二个循环中的每个“li”标签仅提取页面上第一个实例的详细信息。

对于给定的 URL,'month_year' 不会改变,这很好。但是'broadcast' 应该为每个'li' 标签返回不同的细节。

对新手有什么建议吗?

import csv
from bs4 import BeautifulSoup
from urllib.request import urlopen


contents = []
with open('monthly_list.csv','r') as csvf:
    urls = csv.reader(csvf)
    for url in urls:
        page = urlopen(url[0]).read()
        tunes = BeautifulSoup(page, 'html.parser')
        playlist = tunes.find('ul', class_='content-container row')
        daily_URLs_data = open('daily_URLs_2007-2018.csv', 'a')
        for li in playlist.find_all('div', class_='description'):
            month_year = tunes.find('div', class_='resultsHeader').text
            broadcast = playlist.h3.a
            print (month_year)
            print (broadcast)
            csv_writer.writerow([month_year, broadcast])

标签: pythonbeautifulsoup

解决方案


推荐阅读