0

XMLファイルから<item> </item>でくくられている文を抽出したいです。

以下の正規表現を使って一個ずつなら抽出することができたのですが、<item><title>([^<]*)</title></item>のようにしてitemの中のtitleを抽出する正規表現をご存じの方いませんか?

  • find tilte: <title>([^<]*)</title>
  • find pic: <media:content([^<]*)/>
  • find description: <description>([^<]*)</description>
  • find URL: <link>([^<]*)</link>
  • find date: <pubDate>([^<]*)</pubDate>

まだプログラミングを始めたばかりで説明文も至らない点ばかりだと思いますが、どうかよろしくお願いします。🙇

対象のXMLファイル

XMLファイル

1
  • 4
    質問には画像でなくテキストを載せるほうがよいです。また, 特定の項目取り出すのに (この場合では)正規表現以外の方法もあるので, 正規表現の使い方を知りたいのか項目を取り出す方法知りたいのかで答えが異なります
    – oriri
    Commented 2022年6月3日 9:41

3 件の回答 3

0

(正規表現関係なく)項目取り出すのなら

from bs4 import BeautifulSoup

soup = BeautifulSoup(xml_string, 'xml')
for item in soup('item'):
    print(item.title.string)

# (出力例)
# CubeSat Set to Demonstrate NASA’s Fastest Laser Link from Space

XML parserなど先にインストールが必要

参考: BeautifulSoupドキュメント Installing a parser

0

RSSのデータらしいので、専用のモジュールが簡単でしょう。
PythonでRSSのスクレイピングする

feedparserを使う
RSSのフォーマットを意識せずにスクレイピングできる。RSSフィードには、RSS1.0, RSS2.0,Atomなど複数フォーマットがあって、めんどくさいので、おすすめ。

上記記事を応用すると以下のように出来るでしょう。

import feedparser

d = feedparser.parse('https://feed.cnet.com/feed/news')

for entry in d.entries:
    print(entry.title)
    print(entry.media_content[0]['url'])
    print(entry.summary)
    print(entry.link)
    print(entry.published)

サイトでは無くファイルから読みたいのであれば url の部分をファイルパスにすれば良いでしょう。

d = feedparser.parse('path/to/file')
0

正規表現に拘るのであれば、以下の様にも書くことができます。

import requests
import re
import html
from pprint import pprint

url = 'http://feed.cnet.com/feed/news'
r = requests.get(url)

rx = re.compile(
    r'<item>.*?<title>(?P<title>.*?)</title>.*?'
    r'<link>(?P<URL>.*?)</link>.*?'
    r'<pubDate>(?P<date>.*?)</pubDate>.*?'
    r'<description>(?P<description>.*?)</description>.*?'
    r'<media:content (?P<pic>.*?)/>')
articles = re.finditer(rx, html.unescape(r.text))
articles = [m.groupdict() for m in articles]
pprint(articles, sort_dicts=False, width=200)

#
[{'title': "Disney's 'Ultra Violet & Black Scorpion' Is a Latinx Superhero Comedy     - CNET",
  'URL': 'https://www.cnet.com/culture/entertainment/disneys-ultra-violet-black-scorpion-is-a-latinx-superhero-comedy/#ftag=CAD590a51e',
  'date': 'Sat, 04 Jun 2022 00:14:32 +0000',
  'description': 'A Mexican American teenager chosen by a magical luchador mask transforms into the superhero Ultra Violet.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/50da35df851159f3d789a18bc7ff3a9e320605db/2022/06/01/f696a896-0f8c-4978-a3d4-0ce186590560/21-04-11-marianna-burelli-l3-303.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': 'Best Fitbit Deals: Save $100 Off Sense, $66 Off Verse 3, $40 Off Charge 4 and More     - CNET',
  'URL': 'https://www.cnet.com/tech/mobile/best-fitbit-deals/#ftag=CAD590a51e',
  'date': 'Sat, 04 Jun 2022 00:00:02 +0000',
  'description': 'Save money on Fitbit fitness trackers that can help you keep track of progress as you work toward your wellness goals.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/ddc5e1e04b80eaac9e5158f8b3b26758049bcb1c/2020/09/29/c2805dc5-0667-43dd-89da-cc1238037ce9/fitbitsense-1.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "NASA Prepares to Solve 'Lunar Mystery' With New Moon Explorer     - CNET",
  'URL': 'https://www.cnet.com/science/space/nasa-prepares-to-solve-lunar-mystery-with-new-moon-explorer/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 23:14:47 +0000',
  'description': 'Oh, and the agency is also sending a bunch of yeast to the lunar surface to see what happens.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/a514e6df024dec5d2b836712ddda191662cd73af/2022/06/03/d0efa718-2eee-41bd-8cbd-0f9151908cbd/domes-lunar.png?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': 'HBO Max: The 39 Best TV Shows to Watch     - CNET',
  'URL': 'https://www.cnet.com/culture/entertainment/hbo-max-the-39-best-tv-series-to-stream-today/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 22:55:00 +0000',
  'description': 'Season 2 of acclaimed comedy-drama Hacks just wrapped up. Here are all the best shows to watch on HBO Max.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/2dc7755ed699878b55265d54a67e554fd15e2256/2022/06/03/17a5cab5-d9e7-460b-82ee-b30e6292088c/jean-smart-0.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': 'Best Printer for 2022     - CNET',
  'URL': 'https://www.cnet.com/tech/computing/best-printer/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 22:00:04 +0000',
  'description': "Whether you're producing documents, photos or both, we've got the perfect printer for you.",
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/9c2932a5bbbcb5dac84566bebe0d7be41211fd63/2018/06/19/07b384fa-e451-46c3-9155-2a434e022dcd/10-brother-hl-3170cdw-digital-color-printer.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "ISS Cosmonaut Spots Whimsical Space 'Stowaways'     - CNET",
  'URL': 'https://www.cnet.com/science/space/iss-cosmonaut-spots-whimsical-space-stowaways/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 21:39:56 +0000',
  'description': "Thank goodness it's not Daleks.",
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/b5d5cff3c111ff2a6de480b83222a803b664cf8d/2022/06/03/12312191-ed6a-4afd-a2f3-e7d10dbb8a6a/progress1.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "Epson Has Some 'Epic' Projector Deals Ahead of National Movie Night on June 10     - CNET",
  'URL': 'https://www.cnet.com/tech/home-entertainment/epson-is-has-some-epic-projector-deals-ahead-of-national-movie-night-on-june-10th/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 21:13:00 +0000',
  'description': 'Epic may be a slight exaggeration, but you can get up to $200 off some pretty decent mini laser projectors.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/737453d7893337af66b61bc0da4dde234dc864ef/2020/12/17/ba98bcac-d286-4b39-b9ca-f9d8a33289d9/epson-ef12-11-of-10.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "Kesha Embraces the Paranormal in Teaser for New Ghost-Hunting Series 'Conjuring Kesha'     - CNET",
  'URL': 'https://www.cnet.com/culture/entertainment/kesha-embraces-the-paranormal-in-teaser-for-new-ghost-hunting-series-conjuring-kesha/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 21:04:00 +0000',
  'description': 'The Discovery Plus show crosses into our realm on July 8.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/29f9d8ae31fbc27237ccff3fe0dd3a241c0ac0ff/2022/06/03/698b5567-73ee-43a5-9566-75c6973c674d/screen-shot-2022-06-03-at-3-26-59-pm.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': 'Electronics Right to Repair Law Passed     - CNET',
  'URL': 'https://www.cnet.com/tech/mobile/electronics-right-to-repair-law-passed/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 20:58:00 +0000',
  'description': 'New York passes legislation requiring manufacturers to provide repair info and tools to third parties.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/a756c27767d05d683f27a494cc19891b9998dd06/2016/04/06/d3315358-96a1-4ad7-8d7a-2aeaf372c8b9/samsung-s7-broken-phone.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "Scientists' Optical Illusion Will Trick Your Eyes     - CNET",
  'URL': 'https://www.cnet.com/science/biology/scientists-discover-a-black-hole-illusion-that-will-trick-your-brain-and-your-eyes/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 20:51:00 +0000',
  'description': 'Your pupils might speak louder than words when it comes to this brain-melting artwork.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/50861dd4a4c9c0c0efdb5a53ebb8ab4d0b1b6eac/2020/02/25/8182d744-e26d-45dc-a3ef-c594acbed7c5/laptop-eye.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "In a World First, Scientists Transplant 3D-Printed 'Living Ear' Onto Patient     - CNET",
  'URL': 'https://www.cnet.com/science/biology/doctors-3d-print-living-ear-and-transplant-into-patient/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 20:46:00 +0000',
  'description': '"I\'ve actually been waiting for this my whole career," says lead surgeon Arturo Bonilla.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/81082e3f44b8fb326c8cdd24d0575ce58b346567/2022/06/02/f632de0b-5cd1-434c-8a14-ac81c77586e9/ear-2.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': 'Satellite Data Shows Global Warming Turning the Alps From White to Green     - CNET',
  'URL': 'https://www.cnet.com/science/climate/satellite-images-show-global-warmings-extreme-impact-on-the-alps/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 20:44:00 +0000',
  'description': 'The mountain range famous for its snowcapped peaks has been developing a blanket of vegetation.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/9110871c75fac5ad45228de639001cb38693f352/2022/06/02/6a81e001-591b-48fa-afb8-2e66d2b0f0b8/low-res-swiss-alpes-srumpf-jpg.png?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "How to Watch Blue Origin's Latest Crewed Launch Saturday     - CNET",
  'URL': 'https://www.cnet.com/science/space/how-to-watch-blue-origins-latest-crewed-launch-saturday/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 20:40:53 +0000',
  'description': 'The New Shepard rocket will send six people out of this world to start the weekend.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/f0ecde1f638302d01b67bdad38584eeb11a5d929/2021/12/11/acc8c2e6-043f-4b49-9448-339ac75fd76f/blue-origin-image-final.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "'Obi-Wan Kenobi': Release Schedule, Plot, Moses Ingram and Everything to Know     - CNET",
  'URL': 'https://www.cnet.com/culture/entertainment/obi-wan-kenobi-release-schedule-plot-moses-ingram-and-everything-to-know/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 20:37:00 +0000',
  'description': "Ewan McGregor's beloved Jedi master and his fallen apprentice Darth Vader are back in the Disney Plus Star Wars series. Here are the trailers and all the info you need.",
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/2d81a10f844e9f5c6c15fc617eafb21391c8ce6b/2022/06/03/2fee3445-8130-41f5-8d9a-5d969db6444f/jtf-ff-000556.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "'Top Gun: Maverick' Isn't Streaming, Sorry (and It Won't for a While)     - CNET",
  'URL': 'https://www.cnet.com/tech/services-and-software/top-gun-maverick-isnt-streaming-sorry-and-wont-for-a-while/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 20:20:00 +0000',
  'description': "Top Gun: Maverick is destined for Paramount Plus, but it'll be sticking to theaters until mid-July at least -- and maybe longer. Here's what to know.",
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/425ff75c2574ef2851e1521c35f5b5e0eb933942/2022/05/11/007be1fb-95a3-4ca1-b933-59bdd8606527/top-gun-maverick-tom-cruise-tgm-41668r-cr2-promo.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "'Doctor Strange' Will Stream Before 'Spider-Man: No Way Home'? Here's Why     - CNET",
  'URL': 'https://www.cnet.com/tech/services-and-software/doctor-strange-to-stream-before-spider-man-no-way-home-heres-why/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 20:02:00 +0000',
  'description': "Spider-Man: No Way Home hit theaters in December. Doctor Strange, in May. But Strange will be streaming weeks before Spider-Man does. What's going on?",
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/3554e2daefac247da5c8664a72d4fb5bb5b6efc5/2022/06/03/4398d55d-3872-4856-9b3e-d591d6cb5e9d/spider-man-no-way-home-centered.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': 'Former OpenSea Manager Charged With Insider NFT Trading     - CNET',
  'URL': 'https://www.cnet.com/personal-finance/crypto/former-opensea-manager-charged-with-insider-nft-trading/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 19:41:00 +0000',
  'description': 'This marks the first time the DOJ has filed an indictment in connection with alleged insider trading of digital assets.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/77e4e7f7f13414f918395cf1d67c69a2e63b50b9/2022/06/01/e96f9c1b-5abc-47ae-9353-fc14d91f6e00/gettyimages-1237650322.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "NASA Mars Rover Has a 'Pet Rock' in Its Wheel That Refuses to Leave     - CNET",
  'URL': 'https://www.cnet.com/science/space/nasa-mars-rover-has-a-pet-rock-in-its-wheel-that-refuses-to-leave/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 19:39:10 +0000',
  'description': 'After months of adventure, the rock is still along for the ride with Perseverance.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/9e0b3e177500b41d04a501a5741a2bfab894a233/2022/06/03/407a922f-5417-4660-a24e-0440541bf2ab/percyrocklater.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': 'Score Summer Styles for Under $50 at Journeys     - CNET',
  'URL': 'https://www.cnet.com/culture/score-summer-styles-for-under-50-at-journeys/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 19:16:00 +0000',
  'description': 'Get great deals on gear from brand names during this sale.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/aece65c9a31495d4ad46aa9580d2e46666e75327/2022/06/03/d153eb9e-c652-4c40-8736-bd51ace350e0/new-cnet-colors.png?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': 'Mario Strikers: Battle League Online Demo - Times, How to Download and More     - CNET',
  'URL': 'https://www.cnet.com/tech/gaming/mario-strikers-is-holding-online-demo-sessions-next-weekend/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 18:30:05 +0000',
  'description': 'Switch Online members can try the upcoming Mario soccer game early.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/cfdf9f4a44c88a4b1012ffdb29692af3cd9d40bc/2022/05/12/3ad0d43e-47f9-4877-91d9-529d81914087/mario-strikers-battle-league.png?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "Netflix's Biggest Shows and Movies Ever, Ranked (According to Netflix)     - CNET",
  'URL': 'https://www.cnet.com/tech/services-and-software/netflix-biggest-shows-and-movies-ranked-according-to-netflix/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 18:26:00 +0000',
  'description': 'Netflix updates weekly popularity charts, include a ranking of its all-time most watched shows and movies, in hopes of helping you discover something to watch.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/05265c0a34cf7c4ecfa33d2f800970b1e89047d0/2022/04/27/3f286768-6f38-44c1-83a2-2d81f4ad4637/netflix-logo-2022-524.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': 'Sega Reveals Mega Drive Mini 2 for Japan, Will Include CD Games     - CNET',
  'URL': 'https://www.cnet.com/tech/gaming/sega-reveals-mega-drive-mini-2-for-japan-will-include-cd-games/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 18:20:00 +0000',
  'description': 'Still no word on whether the Sega Genesis Mini 2 will come to the US.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/00081989553c3fa31e0bab8c6c589e7de4c219b7/2022/06/03/b15d3bb5-8069-4b92-8159-b109c11f30bb/sega-mega-drive-mini-2.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': 'Best Wi-Fi 6 Routers of 2022     - CNET',
  'URL': 'https://www.cnet.com/news/the-best-wi-fi-6-routers-of-2022/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 18:15:00 +0000',
  'description': "Want to upgrade your home network to 802.11ax, the newest and fastest version of Wi-Fi? You'll need a Wi-Fi 6 router. Here are the best ones.",
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/68e436f2e35551a357ec8167e1b9b28ac140fd69/2021/09/09/0a87d6fe-f393-4f8f-898c-056c7e822eab/tp-link-archer-ax21-ax1800-wi-fi-6-router-blue-promo.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': 'Pokemon Scarlet and Violet: Every New Pokemon Revealed So Far     - CNET',
  'URL': 'https://www.cnet.com/tech/gaming/pokemon-scarlet-and-violet-every-new-pokemon-revealed-so-far/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 18:00:04 +0000',
  'description': 'Take a look at some new Pokemon debuting in the upcoming Nintendo Switch games.',
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/46448b9af0cc05db027a0d1cac58a8549cd5ffe7/2022/03/04/776bdc4d-e9e3-4b84-b68e-dbead523a929/pokemon-scarlet-and-violet.jpg?auto=webp&fit=crop&height=614&width=1092"'},
 {'title': "'Doctor Strange 2' Illuminati, Explained: Who Are These Elite Marvel Heroes?     - CNET",
  'URL': 'https://www.cnet.com/culture/entertainment/doctor-strange-2-illuminati-explained-who-are-these-elite-marvel-heroes/#ftag=CAD590a51e',
  'date': 'Fri, 03 Jun 2022 18:00:02 +0000',
  'description': "The Multiverse of Madness introduces a group of iconic characters, so let's dive into their histories and fates.",
  'pic': 'height="614" width="1092" medium="image" '
         'url="https://www.cnet.com/a/img/resize/fadf272df603d7df34becef089d9f26db75cf29d/2022/04/26/61bc7c4a-5bb8-4dc0-83ff-9360aaca7015/screenshot-2022-04-26-at-10-08-03.png?auto=webp&fit=crop&height=614&width=1092"'}]

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。