【问题标题】:Python - Combine two, single column lists into one dual column list and printPython - 将两个单列列表合并为一个双列列表并打印
【发布时间】:2019-02-06 22:47:40
【问题描述】:

我刚刚开始涉足 Python,正如许多人所做的那样,我从一个网络抓取示例开始尝试该语言。 我见过很多使用 zip 和 map 来组合列表的示例,但是我在尝试打印该列表时遇到了问题。 再说一次,我是新人,所以请温柔。

代码从 2 种特定标签类型(帖子的日期和标题)中收集所有内容,并将它们作为 2 个列表返回。为此,我正在使用 BeautifulSoup 和请求。 我正在练习这个测试的网站是一个名为“Staxel”的小游戏的博客

我可以让我的代码在 for 循环中使用 [soup.find] 和 [print] 打印一个标签的完整列表,但是当我尝试添加要打印的第二个列表时,我只是得到一个没有错误。 有关如何正确打印 2 个列表的任何提示?

我正在寻找类似的输出

进入 2019-01-06 新年

进入 2018-11-30 1.3.52 的 Staxel 更新日志

# import libraries
import requests
import ssl
from bs4 import BeautifulSoup

# set the URL string
quote_page = 'https://blog.playstaxel.com'

# query the website and return the html to give us a 'page' variable
page = requests.get(quote_page)


# parse the html using beautiful soup and store in a variable ... 'soup'
soup = BeautifulSoup(page.content, 'lxml')

# Remove the 'div' of name and get it's value
title_box = soup.find_all('h1',attrs={'class':'entry-title'})
date_box = soup.find_all('span',attrs={'class':'entry-date published'})
titles = [title.text.strip() for title in title_box]
dates = [date.text.strip()for date in date_box]
date_list = zip(dates, titles)
for heading in date_list:
    print ("Entry {}")

【问题讨论】:

    标签: python python-3.x list beautifulsoup


    【解决方案1】:

    问题是您的日期查询返回一个空列表,因此zipped 结果也将为空。要从该页面中提取日期,您需要查找 time 类型的标签,而不是 span,类 entry-date published

    像这样:

    date_box = soup.find_all("time", attrs={"class": "entry-date published"})
    

    所以用下面的代码:

    import requests
    from bs4 import BeautifulSoup
    
    quote_page = "https://blog.playstaxel.com"
    page = requests.get(quote_page)
    soup = BeautifulSoup(page.content, "lxml")
    
    title_box = soup.find_all("h1", attrs={"class": "entry-title"})
    date_box = soup.find_all("time", attrs={"class": "entry-date published"})
    titles = [title.text.strip() for title in title_box]
    dates = [date.text.strip() for date in date_box]
    
    for date, title in zip(dates, titles):
        print(f"{date}: {title}")
    

    结果变成:

    2019-01-10:Magic 更新 - 功能预览 2019-01-06:新年 2018-11-30:Staxel 1.3.52 更新日志 2018-11-13:Staxel 1.3.49 更新日志 2018-10-21:Staxel 1.3.48 更新日志 2018-10-12:万圣节更新和GOG

    【讨论】:

    • 抱歉,是的,'span' 类型而不是 'time' 类型是我的混淆。实际上,我之前已经运行过正确返回的结果。对我来说,这里的启示是最后一个-for-循环,其中调用了日期和标题,然后在打印命令中明确说明。感谢您的代码更正。很有帮助。
    猜你喜欢
    • 2014-01-27
    • 2014-05-16
    • 2019-02-05
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多