python - BeautifulSoup 元素输出到列表

标签 python html web-scraping beautifulsoup

我有一个使用 BeautifulSoup 的输出。

  1. 我需要将 'type' 'bs4.element.Tag' 的输出转换为列表,并将该列表导出到名为 COLUMN_A 的 DataFrame 列中

  2. 我希望我的输出在第 14 个元素处停止(最后三个 h2 没有用)

我的代码:

import requests
from bs4 import BeautifulSoup


url = 'https://www.planetware.com/tourist-attractions-/oslo-n-osl-oslo.htm'
url_get = requests.get(url)
soup = BeautifulSoup(url_get.content, 'html.parser')
attraction_place=soup.find_all('h2', class_="sitename")    

for attraction in attraction_place:
    print(attraction.text)
    type(attraction)

输出:

1  Vigeland Sculpture Park
2  Akershus Fortress
3  Viking Ship Museum
4  The National Museum
5  Munch Museum
6  Royal Palace
7  The Museum of Cultural History
8  Fram Museum
9  Holmenkollen Ski Jump and Museum
10  Oslo Cathedral
11  City Hall (Rådhuset)
12  Aker Brygge
13  Natural History Museum & Botanical Gardens
14  Oslo Opera House and Annual Music Festivals
Where to Stay in Oslo for Sightseeing
Tips and Tours: How to Make the Most of Your Visit to Oslo
More Related Articles on PlanetWare.com

我希望这样的列表:

attraction=[Vigeland Sculpture Park, Akershus Fortress, ......]

非常感谢您。

最佳答案

一个不错的简单方法是采用照片的 alt 属性。这将获得干净的文本输出,并且只有 14 个,无需任何切片/索引。

from bs4 import BeautifulSoup
import requests

r = requests.get('https://www.planetware.com/tourist-attractions-/oslo-n-osl-oslo.htm')
soup = bs(r.content, 'lxml')
attractions = [item['alt'] for item in soup.select('.photo [alt]')]
print(attractions)

关于python - BeautifulSoup 元素输出到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56468212/

相关文章:

node.js - 从 NodeJS 服务器获取实时流音频到客户端

python - “列表”对象在遍历 WebElements 时没有属性 'get_attribute'

python - sessionmaker 错误

python - 复杂消息结构解析器的设计

python - 特拉维斯 + 应用程序

python - tensorflow 中的求和池

html - CSS:网页设计,第 182 页,字间距和对齐

html - 边距顶部分辨率 css

涉及 HTML a 标签的 Python 网络抓取

json - 如何将 VBA-JSON 输出移动到工作表中的特定单元格?