2016-11-02 2 views
-1

나는 div35에서 모든 링크를 얻기 위해 class = "pntc-txt"인 코드를 작성하고 <a> 태그 href 속성과 <a href="">Something</a> 사이의 텍스트 이후에 해당 URL과 텍스트를 가져 와서 데이터베이스에 삽입하십시오.<a>에서 URL과 제목을 얻는 방법 beautifulSoup로 태그

import urllib.request 
from bs4 import * 

sock = urllib.request.urlopen("http://as.com/tag/moto_gp/a/") 
htmlSource = sock.read()        
sock.close()           

soup = BeautifulSoup(htmlSource) 


for div in soup.findAll('div', {'class': 'pntc-txt'}): 
    a = div.findAll('a') 
    print (a) 
+1

여기에 완전히 설명되어 있습니다. https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes –

답변

0

이 시도 :

import requests 
from bs4 import * 

srcCode = requests.get("http://as.com/tag/moto_gp/a/") 
plainText = srcCode.text 

soup = BeautifulSoup(plainText) 


for div in soup.findAll('div', {'class': 'pntc-txt'}): 
    for each in div.findAll('a'):  #get all elements with 'a' tag 
     href = each.get('href') 
     print href   #print href 
     print each.string #print the text in tags 
     print each   #print whole tag 

: 또한 HTML 페이지를 읽기 위해 URLLIB 부분을 제거 내가 지금까지 수행 한 코드를 게시 할 수 있습니다. 대신 패키지를 사용 requests

+0

ver much! 감사합니다. 그것은 매우 잘 작동 :) – Albert