2017-06-20 1 views
2

私はPythonを使ってthesaurus.comからシノニムを掻き集めようとしています。シノニムを順序付けられていないリストを使ってリストしています。Pythonのhtmlから順序付けられていないリストをスクラップするにはどうすればよいですか?

from lxml import html 
import requests 
term = (input("Enter in a term to find the synonyms of: ")) 
page = requests.get('http://www.thesaurus.com/browse/' + term.lower(),allow_redirects=True) 
if page.status_code == 200: 
    tree = html.fromstring(page.content) 
    synonyms = tree.xpath('//div[@class="relevancy-list"]/text()') 
    print(synonyms) 
else: 
    print("No synonyms found!") 

マイコードでは、同義語の代わりに空白だけが出力されます。スペースの代わりに実際のシノニムをどのように削り取るのですか?

答えて

1

/text()は、現在のタグのすぐ下にテキストを印刷します。したがって、現在のコードでは、同義語はdivタグ内の別のタグの下にあるため、同義語は印刷されません。

//text()を使用して、現在のタグの下にあるすべてのテキストを印刷する必要があります。しかし、これは不要なものを含むすべてのテキストを印刷します。同義語は<span class="text">タグ内なので、あなたはこのXPathを使用することができ、あなたのユースケースについては

、:

クラスを持つdiv要素の中に発見クラス「テキスト」とのスパンの中に発見すべてのテキストを選択し
//div[@class="relevancy-list"]//span[@class="text"]/text() 

"関連性リスト"。あなたが単語のすべての感覚の同義語を取得します

 
['firm', 'bent', 'stated', 'specified', 'rooted', 'established', 'confirmed', 'pat', 'immovable', 'obstinate', 'ironclad', 'predetermined', 'intent', 'entrenched', 'appointed', 'regular', 'prescribed', 'determined', 'scheduled', 'fixed', 'settled', 'certain', 'customary', 'decisive', 'definite', 'inveterate', 'pigheaded', 'resolute', 'rigid', 'steadfast', 'stubborn', 'unflappable', 'usual', 'concluded', 'agreed', 'resolved', 'stipulated', 'arranged', 'prearranged', 'dead set on', 'hanging tough', 'locked in', 'set in stone', 'solid as a rock', 'stiff-necked', 'well-set', 'immovable', 'entrenched', 'located', 'solid', 'situate', 'stiff', 'placed', 'stable', 'fixed', 'settled', 'situated', 'rigid', 'strict', 'stubborn', 'unyielding', 'hidebound', 'positioned', 'sited', 'jelled', 'hard and fast', 'deportment', 'comportment', 'fit', 'presence', 'mien', 'hang', 'carriage', 'air', 'turn', 'attitude', 'address', 'demeanor', 'position', 'inclination', 'port', 'posture', 'setting', 'scene', 'scenery', 'flats', 'stage set', u'mise en sc\xe8ne', 'series', 'array', 'lot', 'collection', 'batch', 'crowd', 'cluster', 'gang', 'bunch', 'crew', 'circle', 'body', 'coterie', 'faction', 'company', 'bundle', 'outfit', 'band', 'clique', 'mob', 'kit', 'class', 'clan', 'compendium', 'clutch', 'camp', 'sect', 'push', 'organization', 'clump', 'assemblage', 'pack', 'gaggle', 'rat pack', 'locate', 'head', 'prepare', 'fix', 'introduce', 'turn', 'settle', 'lay', 'install', 'put', 'apply', 'post', 'establish', 'wedge', 'point', 'lock', 'affix', 'direct', 'rest', 'seat', 'station', 'plop', 'spread', 'lodge', 'situate', 'plant', 'park', 'bestow', 'train', 'stick', 'plank', 'arrange', 'insert', 'level', 'plunk', 'mount', 'aim', 'cast', 'deposit', 'ensconce', 'fasten', 'embed', 'anchor', 'make fast', 'make ready', 'zero in', 'appoint', 'name', 'schedule', 'make', 'impose', 'stipulate', 'settle', 'determine', 'establish', 'fix', 'specify', 'designate', 'decree', 'resolve', 'rate', 'conclude', 'price', 'prescribe', 'direct', 'value', 'ordain', 'allocate', 'instruct', 'allot', 'dictate', 'estimate', 'regulate', 'assign', 'arrange', 'lay down', 'agree upon', 'fix price', 'fix', 'stiffen', 'thicken', 'condense', 'jelly', 'clot', 'congeal', 'solidify', 'cake', 'coagulate', 'jell', 'gelatinize', 'crystallize', 'jellify', 'gel', 'become firm', 'gelate', 'drop', 'subside', 'sink', 'vanish', 'dip', 'disappear', 'descend', 'go down', 'initiate', 'begin', 'raise', 'abet', 'provoke', 'instigate', 'commence', 'foment', 'whip up', 'put in motion', 'set on', 'stir up'] 

注:入力項set、XPathがあることを使用して出力するため

//div[@class="relevancy-list"]の結果を手動でループして、divごとに//span[@class="text"]/text()を抽出し、意味ごとの同義語を取得することができます。すべてliタグを見つける

0
import requests 
from bs4 import BeautifulSoup 

term = input("Enter in a term to find the synonyms of: ") 
page = requests.get('http://www.thesaurus.com/browse/' + term.lower(), allow_redirects=True) 

if page.status_code == 200: 
    soup = BeautifulSoup(page.content, 'html.parser') 
    get_syn_tag = soup.find('div', {'class': 'relevancy-list'}) 
    list_items = get_syn_tag.findAll('li') 
    synonyms = [] # to fetch synonym anytime used list to append all synonyms 
    for i in list_items: 
     synonym = i.find('span', {'class':'text'}).text 
     print(synonym) # prints single synonym on each iteration 
     synonyms.append(synonym) # appends synonym to list 
else: 
    print("No synonyms found!") 

しかしも動作しますラインの下に、この場合には、より正確には次のとおりです。

synonym_list = [i.text for i in get_syn_tag.findAll('span', {'class':'text'})] # this will create a list of all available synonyms if there is no other `span` tag with same class `text` in the specified `div` 
関連する問題