2016-05-16 26 views
0

我在「op.gg」網站上使用正則表達式抓取遊戲玩家的名稱。Python網絡抓取和正則表達式

我用reqexr.com網站來檢查我想要得到的東西的正則表達式,我找到了200名玩家。

但我的python代碼不起作用。我打算將200個數據插入列表中。但列表是空的。

我認爲單引號(')不適用於我的Python代碼。

這裏是我的一塊代碼..

import requests 
from bs4 import BeautifulSoup 
import re 

user_name = input() 

def hex_user_name(user_name): 
    hex_user_name = [hex(x) for x in user_name.encode('utf-8')] 
    for i,j in enumerate(hex_user_name): 
     hex_user_name[i] = '%'+j[2:].upper() 
    return ''.join(hex_user_name) 

def get_user_name(user_name): 
    q = re.compile('k\'>([^<]{1,16})', re.M) 
    site = 'http://www.op.gg/summoner/userName=' + user_name 
    source_code = requests.get(site) 
    plain_text = source_code.text 
    soup = BeautifulSoup(plain_text, 'lxml') 
    name = soup.find_all('a') 
    listB = q.findall(re.sub('[\s\n,]*', '' ,str(name))) 
    print(listB) 

get_user_name(hex_user_name(user_name)) 

我強烈懷疑這行

q = re.compile('k\'>([^<]{1,16})', re.M) 

有問題..但我找不到任何錯誤。

這是我想對正則表達式中使用的:k\'>([^<]*)

而且이곳은지옥인가(韓字)是我想要得到的HTML代碼中的數據。

<div class="SummonerName"> 
     <a href="//www.op.gg/summoner/userName=%EC%9D%B4%EA%B3%B3%EC%9D%80%EC%A7%80%EC%98%A5%EC%9D%B8%EA%B0%80" class="Link" target='_blank'>이곳은지옥인가</a> 
</div> 

我真的很感謝你們幫我了..

回答

0

你的正則表達式工作

>>> x = ('<a href="//www.op.gg/summoner/userName=%EC%9D%B4%EA%B3%B3%EC%9D' 
     '%80%EC%A7%80%EC%98%A5%EC%9D%B8%EA%B0%80" class="Link" ' 
     'target=\'_blank\'>이곳은지옥인가</a>') 
>>> import re 
>>> q = re.compile('k\'>([^<]{1,16})', re.M) 
>>> q.findall(x) 
['이곳은지옥인가'] 

也許足夠plain_text你的正則表達式

listB = q.findall(re.sub('[\s\n,]*', '' , plain_text)) 

因爲soup.find_all('a')returns a list,所以你需要循環。

強制轉換列表爲str CA會導致混亂,因爲它會逃跑的'和/或"

>>> li = ['k\'b"n', 'sdd'] 
>>> str(li) 
'[\'k\\\'b"n\', \'sdd\']' 
>>> 
>>> li 
['k\'b"n', 'sdd'] 
>>> 
>>> 
>>> li = ["k'b\"n", 'sdd'] 
>>> li 
['k\'b"n', 'sdd'] 
>>> str(li) 
'[\'k\\\'b"n\', \'sdd\']' 
>>> 

這將很容易破壞你的正則表達式。