Skip to main content
 首页 » 编程设计

python之BeautifulSoup 爬虫解析

2024年09月07日9开发

我正在尝试使用 bs4 制作爬虫 这是我要从中抓取数据的目标页面

http://sports.news.naver.com/wfootball/news/index.nhn?page=1

这是我要获取的数据

<html>~~ 
<head>...</head> 
<body> 
    <some several layer...> 
        <div class="news_list" id="_newsList"> 
            <h3 class="blind"> ~ </h3> 
            <ul> 
                <li> 
                    <div class="text"> 
                        <a href="~~~~"> 
                            <span>"**targetData**"</span> 
                </li> 
                <li> 
                    same structure 
                </li> 
                <li>...</li> 
                several <li>...</li> 
            </ul> 
        </div> 
    </layers...> 
</body> 
</html> 

这是我的代码

#-*- coding: utf-8 -*- 
import urllib 
from bs4 import BeautifulSoup 
 
targettrl = 'http://sports.news.naver.com/wfootball/news/index.nhn?page=1' 
soup = BeautifulSoup(urllib.urlopen(targettrl).read(), 'html.parser') 
print(soup.find_all("div", {"class":"news_list"})) 

结果

[] 

我该怎么办?

请您参考如下方法:

您想要的内容是使用 JavaScript 动态加载的,因此在 <div> 内的页面源代码中找不到。您正在搜索的标签。但是,数据在 <script> 内的页面源中可用。 JSON格式的标签。

你可以使用这个来抓取它:

import re 
import json 
import requests 
 
r = requests.get('http://sports.news.naver.com/wfootball/news/index.nhn?page=1') 
script = re.findall('newsListModel:(.*})', r.text)[0] 
data = json.loads(script) 
 
for item in data['list']: 
    print(item['title']) 
    url = 'http://sports.news.naver.com/wfootball/news/read.nhn?oid={}&aid={}'.format(item['oid'], item['aid']) 
    print(url) 

输出:

‘로마 영웅’ 제코, “첼시 거절? 돈이 중요하지 않아” 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=139&aid=0002089601 
손흥민, 맨시티전 선발 전망...'시즌 19호' 기대(英 매체) 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=139&aid=0002089600 
드디어 정해진 UCL 4강 진출팀, 4강 대진은 과연? 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=047&aid=0002185662 
극적 승리 후 ‘유물급 분수대’에 뛰어든 로마 구단주 벌금형 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=081&aid=0002907313 
'토너먼트의 남자' 호날두, 팀 득점 6할 책임지다 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=216&aid=0000094120 
맨유 스카우트 파견...타깃은 기성용 동료 수비수 모슨 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=139&aid=0002089598 
이번에는 '타점', 늘 새로운 호날두의 키워드 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=413&aid=0000064740 
승무패 14회차, 토트넘 홈에서 맨시티 이길 것 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=396&aid=0000477162 
3부까지 추락했던 울버햄튼, 6년 만에 EPL 승격 눈앞 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=413&aid=0000064739 
메시 밀어낸 호날두…역대 챔스리그 한 시즌 최다골 1∼3위 독식(종합) 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=001&aid=0010020684 
‘에어 호날두’ 있기에···레알 8년 연속 챔스 4강 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=011&aid=0003268539 
[UEL] '황희찬 복귀' 잘츠부르크, 역전 드라마 가능할까? 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=436&aid=0000028419 
[UCL 포커스] 호날두 환상골도, 만주키치 저력도, 부폰에 묻혔다 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=139&aid=0002089597 
[UCL 핫피플] ‘120골+11G 연속골’ 호날두, 역사는 진행형 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=139&aid=0002089596 
[SPO 이슈] ‘재점화’ 케인vs살라, 득점왕 경쟁 포인트3 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=477&aid=0000118254 
UCL 8강 키워드: 공은 둥글다…'3점 차'여도 안심할 수 없었으니까 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=477&aid=0000118253 
"과르디올라, 시즌 종료 전 1년 계약 연장한다" (英 미러) 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=529&aid=0000022390 
케이토토 승무패 14회차 투표율 중간집계 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=382&aid=0000638196 
‘월드컵 스카우팅 리포트 2018’ 발간 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=005&aid=0001088317 
레알 마드리드, 천신만고 끝에 챔피언스리그 4강 
http://sports.news.naver.com/wfootball/news/read.nhn?oid=052&aid=0001134496 

在这里,item是具有以下格式的字典:

{'aid': '0002185662', 
 'datetime': '2018.04.12 14:09', 
 'officeName': '오마이뉴스', 
 'oid': '047', 
 'sectionName': '챔스·유로파', 
 'subContent': '최고의 명경기 예약, 추첨은 4월 13일 오후 7시[오마이뉴스 이윤파 기자]이변이 가득했던 17-18 UEFA 챔피언스리그 8강이 모두 끝나고 4강 진출 팀...', 
 'thumbnail': 'http://imgnews.naver.net/image/thumb154/047/2018/04/12/2185662.jpg', 
 'title': '드디어 정해진 UCL 4강 진출팀, 4강 대진은 과연?', 
 'totalCount': 0, 
 'type': 'PHOTO', 
 'url': None} 

因此,您可以使用它访问任何您想要的内容。只需替换 ['title']随心所欲。每个<li>里面的所有东西标签在字典中可用。