抓取多个页面标题的Python问题

时间:2020-06-11 15:36:03

标签: python beautifulsoup

我是一名营销人员,希望使用Python进行一些基本的市场研究。

我编写了一个简单的代码来爬网标题的多个页面,但是将标题文本放入列表并将其转换为Excel格式无效。在这种情况下该怎么办?
我尝试创建一个list并使用extend()方法将这些循环标题放在列表中,但是没有用:

import requests
import pandas as pd
from bs4 import BeautifulSoup

def content_get(url):
    count = 0
    while count < 4:                 #this case was to crawl titles of 4 pages
        r = requests.get(url)
        soup = BeautifulSoup(r.content, "html.parser")
        titles = soup.find(id="main-container").find_all("div", class_="r-ent")
        for title in titles:
            print([title.find('div', class_='title').text])
        nextpageurl = soup.find("a", string="‹ 上頁")["href"]
        url = "https://www.ptt.cc" + nextpageurl
        count += 1

firstpage = "https://www.ptt.cc/bbs/movie/index9002.html"
content_get(firstpage)

1 个答案:

答案 0 :(得分:0)

您需要将标题添加到while循环之外的列表中:

def content_get(url):
    count = 0
    titles = []

    while count < 4:                
        r = requests.get(url)
        soup = BeautifulSoup(r.text)

        title_page = [title.text.replace('\n', '') for title in soup.find_all('div', {'class': 'title'})]            
        titles.extend(title_page)

        nextpageurl = soup.find("a", string="‹ 上頁")["href"]
        url = "https://www.ptt.cc" + nextpageurl
        count += 1
    return titles

如果您不希望列表理解获得titles_page,则可以用传统的for循环代替:

titles_page = []
titles = soup.find_all('div', {'class': 'title'})
for title in titles:
    titles_page.append(title.text.replace('\n', ''))

对于excel文件:

def to_excel(text):
    df = pd.DataFrame(text, columns=['Title'])
    return df.to_excel('output.xlsx')