如果我理解正確,你從某處獲取html頁面並且想要提取所有鏈接的twitter用戶?您可以解析html代碼,也可以使用一些字符串拆分來完成此操作。此代碼是未經測試,但應該給你一個想法:
$input = '(the html code)';
$links = explode('<a ', $input); //split input by start of link tags
for ($i = 0; $i < count($links); $i++) {
//cut off everything after the closing '>'
$links[$i] = explode('>', $links[$i], 2)[0]
//skip this link if it doesn't go to twitter.com
if (strpos($links[$i], 'href="twitter.com/') === False) { continue; }
//split by the 'href' attribute and keep everything after 'twitter.com'
$links[$i] = explode('href="twitter.com/', $links[$i], 2)[1]
//cut off everything after the " ending the href attribute
$links[$i] = explode('"', $links[$i], 2)[0]
//now $links[$i] should contain the twitter username
echo $links[$i]
}
注:如果有其他鏈接到Twitter是不是主要頁面或用戶頁面上,他們將獲得印太(例如,如果頁面鏈接到twitter常見問題)。你需要手動過濾它們。
php糟透了,讓我們在python中做到這一點!
input = '(the html code)'
links = [l.split(">", 1)[0] for l in input.split("<a ")}
twitter_links = [l for l in links if 'href="twitter.com/' in l]
twitter_hrefs = [l.split('href="twitter.com/', 1)[1] for l in twitter_links]
users = [l.split('"', 1)[0] for l in twitter_hrefs]
print '\n'.join(users)
什麼是「多」?什麼是「$名稱」? – tomsv
多意味着有更多的元素來解析像 – LeoSam
他意味着多個元素。 – Asciiom