ユニークなIDを持つテキストファイルに100万件の奇妙なURLと検索語句があります。 URLを開いてsearchtermsを検索する必要があります。存在する場合は1
、それ以外の場合は0
となります。URLエラーの単語を検索する
入力ファイル:
"ID" "URL","SearchTerm1","Searchterm2"
"1","www.google.com","a","b"
"2","www.yahoo.com","f","g"
"3","www.att.net","k"
"4" , "www.facebook.com","cs","ee"
コードスニペット:
import urllib2
import re
import csv
import datetime
from BeautifulSoup import BeautifulSoup
with open('txt.txt') as inputFile, open ('results.txt','w+') as proc_seqf:
header = 'Id' + '\t' + 'URL' + '\t'
for i in range(1,3):
header += 'Found_Search' + str(i) + '\t'
header += '\n'
proc_seqf.write(header)
for line in inputFile:
line=line.split(",")
url = 'http://' + line[1]
req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"})
html_content = urllib2.urlopen(req).read()
soup = BeautifulSoup(html_content)
if line[2][0:1] == '"' and line[2][-1:] == '"':
line[2] = line[2][1:-1]
matches = soup(text=re.compile(line[2]))
#print soup(text=re.compile(line[2]))
#print matches
if len(matches) == 0 or line[2].isspace() == True:
output_1 =0
else:
output_1 =1
#print output_1
#print line[2]
if line[3][0:1] == '"' and line[3][-1:] == '"':
line[3] = line[3][1:-1]
matches = soup(text=re.compile(line[3]))
if len(matches) == 0 or line[3].isspace() == True:
output_2 =0
else:
output_2 =1
#print output_2
#print line[3]
proc_seqf.write("{}\t{}\t{}\t{}\n".format(line[0],url,output_1, output_2))
出力ファイル:コードで
ID,SearchTerm1,Searchterm2
1,0,1
2,1,0
3,0
4,1,1
2つの問題:
私は約200 URLを一度に実行すると、
urlopen error [Errno 11004] getaddrinfo failed error
となります。正確には一致するものの、正確には一致しないものを検索する方法はありますか?
なぜ反対票:
だからあなたは、このようなオプションの末尾のドットに一致するように正規表現を構築するだろうか? – Zack
私は、理由が閉鎖投票で示唆されていると思う:広すぎる。あなたは1回の投稿で3つの質問をしました。そのうちの2番目は実際にはStack OverflowではなくCode Reviewに属しています。 – Prune
@Pruneコードに変更を加えていただきありがとうございます。 – Zack