파이썬으로 url이 담긴 텍스트파일을 읽어서 크롤링 하는 문제
조회수 2328회
파이썬으로 네이버 평점 과 한줄평들을 저장하는 코드를 작성 해 보았는데요, 이상하게 텍스트 파일의 첫번째와 마지막줄의 url 만 정상적으로 코드가 실행 되는것 같습니다. ㅠㅠ 대체 문제가 뭘까요..? ㅠ 파이썬 첨사용하는 어린이라 많은 지적질 부탁드립니다...
from urllib.error import HTTPError
import requests
import time
from bs4 import BeautifulSoup
def getData(url):
req = requests.get(url)
html = req.text
soup = BeautifulSoup(html, 'html.parser')
sentence = soup.select('div.reporter_line > dl > dd')
score = soup.select('div.re_score_grp > div > div > em')
for score_value, value in zip(score, sentence):
print(value.text, score_value.text)
small_sc = soup.select('li > div.star_score > em')
small_se = soup.select('div.score_reple > p')
for score_value, value in zip(small_sc, small_se):
print(value.text, score_value.text)
file = open('url.txt','r')#txt파일 안에 가져올 url이 한줄씩 있습니다.
for url in file:
print(url)
getData(url)
실행결과 ...
https://movie.na...//url
거두절미 올해 최고의 걸작 9.75
이토록 단순하고 묵직한 감동 9
두려울 정도로 경이롭고 아름답다 9.5
단언컨대, 아이맥스 3D로 8.75
지구영화를 과거의 것으로 만들 진짜 우주영화의 도래 7
우주 속 여성 실존 고투, 건조 단순해도 외로움이 힘! 7
어떤 영화는 관람이 아니라 체험된다. 경이롭다 10
허풍도 적절한 ‘우주 서커스’ 8
압도적인 비주얼과 긴박한 조난극으로 전하는 다시 사는 삶! 9
https://movie.na...//url
이부분에 윗부분처럼 내용이 있어야하는데 안나오네요 ㅠㅠ
https://movie.na..//url
.
.
.
마지막줄 입니다.
https://movie.na..//url
재미있고 제대로 입체적인 3D 애니
7.75
[쿵푸 팬더]와 쌍두마차
7.75
나라면 이크란 대신 투슬리스를 타겠다 8
아아아. 더 날게 해줘 8
고양이를 키우는 사람들이라면 열광하지 않을 수 없다 7
드림웍스의 쾌거 9
OMG, 용과 사랑에 빠지게 될 줄이야 8
온 가족이 훨훨 날아보시라 7
드림웍스도 이제 작품을 만드는구나 7
<아바타>보다 신나는 3D도 있다 7
그러니까, 가끔은 3D로 봐야만 하는 영화가 있어요 8
1 답변
-
사용 라이브러리를 requests 에서 from urllib.request import urlopen 로 바꾸니 해결되었습니다 ㅎㅎ 혹시 몰라서 해본것인데 다행히 잘 동작하네요. 환경은 파이썬 3.7이였구요 파이참으로 실행한거입니다~ 좋은 하루 되세요!
from urllib.request import urlopen #import requests from bs4 import BeautifulSoup def getData(url): webpage = urlopen(url) soup = BeautifulSoup(webpage, 'html.parser') file = open('data.txt','a') sentence = soup.select('div.reporter_line > dl > dd') score = soup.select('div.re_score_grp > div > div > em') for score_value, value in zip(score, sentence): print(value.text.strip(), score_value.text.strip()) file.writelines(value.text.strip().replace(',',' ') +','+ score_value.text.strip() + '\n') small_sc = soup.select('li > div.star_score > em') small_se = soup.select('div.score_reple > p') for score_value, value in zip(small_sc, small_se): print(value.text.strip(), score_value.text.strip()) file.writelines(value.text.strip().replace(',',' ') +','+ score_value.text.strip()+ '\n') file.close() file = open('url.txt','r') for url in file: print(url) getData(url) file.close()
댓글 입력