使用 GAWK
证明使用 gawk 脚本语言是值得的
创建一个文件名gawkscript 并添加以下内容:
#Test to see if the line matches the region, if it does, use regex to get your region
$0~/<td class="xl66" height="17">Channel Islands<\/td>/{printf gensub(/ *<td.*>(.+)<\/td>/,"\\1,",$0)};
#Test to see if the line matches the cose, if it does, use regex to get your code
$0~/<td class="xl66">(.+)<\/td>/{print gensub(/ *<td.*>(.+) *- \(.+\)<\/td>/,"\\1",$0)}
使用你的 shell 你可以运行脚本
gawk -f gawkscript my_html_file
由于这是我们正在处理的 html 代码,我会在 python 调用 BeautifulSoup 中使用一个强大的 html 网页抓取模块
使用 Python
假设你知道一些 python
import re #import regex
from bs4 import BeautifulSoup #import beautifulsoup
soup=BeautifulSoup(
#add your html string
"""<tr height="17">
<td class="xl66" height="17">Channel Islands</td>
<td class="xl66">GY - (Guernsey)</td>
</tr>
<tr height="17">
<td class="xl66" height="17">Channel Islands</td>
<td class="xl66">JE - (Jersey)</td>
</tr>""")
#find all tr tags in your html string
find_all_tr=soup.find_all("tr")
for i in find_all_tr: #loop through all tr tags
all_td=BeautifulSoup(str(i)).find_all("td") #find all td tags
for j in all_td:
#check to see if your td tages matches 'td class="xl66" height="17"' and print
if re.search('<td class="xl66" height="17"',str(j)):
print(j.text.strip(),end=" ")
#check to see if your td tag matches ONLY <td class="xl66" and use regex to obtain your country code
elif re.search('<td class="xl66">',str(j)):
print(","+re.sub(".*-","",j.text.strip()))
注意:我在这里使用 strip() 函数,因为 html 可以在提取信息时消除 html 代码中不需要的换行符