2017-10-09 11 views
0

파이썬을 사용하여 RSS 피드를 읽으려고합니다. 나는 feedparser를 사용하고, 하나를 제외하고, 모든 공급을 위해 잘 작동합니다 https://www.frenchweb.fr/feedFeedparser가 SAXParseException을 반환합니다.

import feedparser 
feed = feedparser.parse("https://www.frenchweb.fr/feed") 
print(feed) 

출력 : 같은 코드에서, 난 그냥 간단한 GET을 할 경우

{ 
    'feed': {}, 
    'entries': [], 
    'bozo': 1, 
    'headers': { 
    'Date': 'Mon, 09 Oct 2017 08:04:31 GMT', 
    'Server': 'Apache', 
    'Vary': 'Cookie,Accept-Encoding', 
    'Expires': 'Thu, 19 Nov 1981 08:52:00 GMT', 
    'Cache-Control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', 
    'Pragma': 'no-cache', 
    'ETag': '"2be89b4a462dd6d1652745b6e69cfdac"', 
    'X-UA-Compatible': 'IE=edge', 
    'Link': '<https://www.frenchweb.fr/wp-json/>; rel="https://api.w.org/"', 
    'Content-Encoding': 'gzip', 
    'Content-Length': '13440', 
    'Connection': 'close', 
    'Content-Type': 'application/rss+xml; charset="UTF-8"' 
    }, 
    'etag': '"2be89b4a462dd6d1652745b6e69cfdac"', 
    'href': 'https://www.frenchweb.fr/feed', 
    'status': 200, 
    'encoding': 'UTF-8', 
    'version': '', 
    'bozo_exception': SAXParseException('XML or text declaration not at start of entity',), 
    'namespaces': {} 
} 

는, 작동, 내가 볼 내용 :

web_page = requests.get(url, headers=headers, allow_redirects=True) 
soup = BeautifulSoup(web_page.content, "html.parser") 
print(soup) 

출력 :

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" 
    xmlns:atom="http://www.w3.org/2005/Atom" 
    xmlns:content="http://purl.org/rss/1.0/modules/content/" 
    xmlns:dc="http://purl.org/dc/elements/1.1/" 
    xmlns:media="http://search.yahoo.com/mrss/" 
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/" 
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" 
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"> 
<channel> 
<title>FrenchWeb.fr</title> 
... 

단서가 있습니까?

답변

1

피드가 잘못되었습니다. 파일의 시작 부분에 개행 문자가 있습니다. 텍스트 편집기에서 다운로드하면, 당신은 그것을 볼 수 있습니다

1 
2 <?xml version="1.0" encoding="UTF-8"?><rss version="2.0" 
3  xmlns:content="http://purl.org/rss/1.0/modules/content/" 
4  xmlns:wfw="http://wellformedweb.org/CommentAPI/" 
5 [...] 

이것은 XML declaration must be on the first line 때문에 문제입니다.

첫 번째 줄 바꿈을 제거하면 작동합니다! 당신은 다음과 같이 첫 번째 줄 바꿈을 삭제할 수 있습니다

{'bozo': 0, 
'encoding': 'utf-8', 
'entries': [{'author': 'FrenchWeb', 
       'author_detail': {'name': 'FrenchWeb'}, 
       'authors': [{'name': 'FrenchWeb'}], 
       'comments': 'https://www.frenchweb.fr/barometre-annuel-de-lexperience-utilisateur-par-kameleoon/305311#respond', 
       'guidislink': False, 
[...] 

편집 해결책 :

import feedparser 
import requests 

url = "https://www.frenchweb.fr/feed" 
headers = [] 
web_page = requests.get(url, headers=headers, allow_redirects=True) 
content = web_page.content.strip() # drop the first newline (if any) 
feed = feedparser.parse(content) 
+0

위대한, 일했다! 도와 주셔서 감사합니다! – iero