2016-11-01 5 views
0

私はウェブサイトからリンク(href)を取得しようとしています。要素は:PythonによるWebスクラップ空白文字列にselect()メソッドを使用する

<a class="overlay no-outline" href="/photos/[email protected]/2834595694/" tabindex="0" role="heading" aria-level="3" aria-label="puppy by mpappas83" data-rapid_p="61" id="yui_3_16_0_1_1477971884605_5513"></a> 

最初に私はクラス"overlay no-outline"と一致させようとしています。 しかし、それには空白があることに注意してください。select()メソッドは、1つではなく2つの異なるセレクタのように扱います。

imgElem= soup.select('.overlay no-outline')  #attempt 

私はこれをどのように達成することができますか?

ウェブサイトでは、これは動作するはずwww.flickr.com

+0

http://stackoverflow.com/questions/34433544/include-multiple-class-names-in-findall-in-beautifulsoup4これはあなたが探しているようです。 –

答えて

1

次のアプローチが役立つはずです:

import bs4 

html = """<a class="overlay no-outline" href="/photos/[email protected]/2834595694/" tabindex="0" role="heading" aria-level="3" aria-label="puppy by mpappas83" data-rapid_p="61" id="yui_3_16_0_1_1477971884605_5513"></a>""" 
soup = bs4.BeautifulSoup(html, "html.parser") 

for link in soup.select("a.overlay.no-outline"): 
    print link['href'] 

を表示する:

/photos/[email protected]/2834595694/   

を間にスペースが2つの異なるクラスを通知するために使用されて適用されている、BeautifulSoup documentationはどのように上の部分を持っています上記の方法でこれに対処してください。 "2つ以上のCSSクラスに一致するタグを検索する場合は"というテキストを探します。

0
import os 
from lxml import html 
import requests 
import fnmatch 

class HtmlRat: 

    def __init__(self): 
     pass 

    def req_page(self, url): 
     page = requests.get(url) 
     return page 

    def tag_data(self, txpath): 
     tag_val = tree1.xpath(txpath + "/text()") 
     val = ''.join(tag_val).strip(' ') 
     val = val.split(' ') 
     return val 

def link_grabber(url, pattern): 
    markup = HtmlRat() 
    tree1 = markup.req_page(url) 
    for tree in tree1: 
     tre = tree.split(" ") 
     for t in tre: 
      if fnmatch.fnmatch(t, pattern): 
       print t 

flickr = link_grabber("https://www.flickr.com/search/?text=cars", 'href="*"') 
superstreet = link_grabber("http://www.superstreetonline.com/features/1610-2013-scion-fr-s-multipurposed/", 'href="*.jpg"') 

# from here you can split it by = to get the links it self. 

です。しかし、私たちがページのソースを読むとき、リンクはそこにはありません。彼らはバックエンドを介して生成されていることを確かめてください。コードを使ってペクセルや他のサイトをチェックしてみてください。