I have a million odd URLs and searches in a text file with a unique identifier. I need to open the urls and find the search queries if they are presented as 1else 0.
Input file:
"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"
Code snippet:
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]))
if len(matches) == 0 or line[2].isspace() == True:
output_1 =0
else:
output_1 =1
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
proc_seqf.write("{}\t{}\t{}\t{}\n".format(line[0],url,output_1, output_2))
output File:
ID,SearchTerm1,Searchterm2
1,0,1
2,1,0
3,0
4,1,1
Two problems with the code: