websucker-pip/mongo/mongocwarler.py

370 lines
12 KiB
Python
Raw Normal View History

2023-03-05 14:44:49 +00:00
import pymongo
import trafilatura
import trafilatura.feeds
import trafilatura.sitemaps
import trafilatura.spider
2023-03-10 12:01:11 +00:00
import trafilatura.utils
2023-03-16 15:06:07 +00:00
import trafilatura.external
2023-03-05 14:44:49 +00:00
import sys
2023-03-07 07:58:28 +00:00
import courlan
2023-03-11 13:14:39 +00:00
import urllib
2023-03-12 05:16:47 +00:00
from datetime import datetime
import click
2023-03-12 08:50:22 +00:00
import logging as LOGGER
import os
2023-03-16 15:06:07 +00:00
import pprint
2023-03-05 14:44:49 +00:00
2023-03-12 08:50:22 +00:00
LANGUAGE= os.getenv("SUCKER_LANGUAGE","sk")
DOMAIN = os.getenv("SUCKER_DOMAIN","sk")
BATCHSIZE=os.getenv("SUCKER_BATCHSIZE",10)
CONNECTION=os.getenv("SUCKER_CONNECTION","mongodb://root:example@localhost:27017/")
DBNAME=os.getenv("SUCKER_DBNAME","crawler")
2023-03-11 13:14:39 +00:00
MINFILESIZE=300
2023-03-12 05:16:47 +00:00
MAXFILESIZE=10000000
MINTEXTSIZE=200
2023-03-05 17:53:14 +00:00
2023-03-17 15:40:55 +00:00
def put_queue(db,channel,message):
queuecol = db["queue"]
queuecol.insert_one({"channel":channel,"message":message,"created_at":datetime.utcnow(),"started_at":None})
def reserve_queue(db,channel,message):
queuecol = db["queue"]
r = queuecol.find_one_and_delete({"channel":channel},sort={"created_at":-1})
def delete_queue(db,channel):
queuecol = db["queue"]
pass
2023-03-07 15:18:32 +00:00
def calculate_checksums(text):
2023-03-05 17:53:14 +00:00
"""
@return fingerprints of a paragraphs in text. Paragraphs are separated by a blank line
"""
checksums = []
sizes = []
hval = 0
hsz = 0
sz = 0
for c in text:
cv = ord(c)
sz += 1
if cv > 64:
hval += (hval << 3) + cv
zv = hval >> 31
hval &= 0x7fffffff
hval += zv
hsz += 1
if c == "\n" and hsz > 0:
if hsz > 100:
checksums.append(hval)
sizes.append(sz)
sz = 0
hsz = 0
if hsz > 100:
checksums.append(hval)
sizes.append(sz)
return checksums, sizes
2023-03-11 10:30:30 +00:00
def is_robot_good(link,rules):
# check robots.txt rules
2023-03-12 08:50:22 +00:00
if rules is not None and not rules.can_fetch("*", link):
2023-03-29 08:17:57 +00:00
print("bad>>>" + link)
2023-03-11 10:30:30 +00:00
return False
return True
def is_link_good(link):
2023-03-11 13:14:39 +00:00
r = courlan.check_url(link,strict=True,language=LANGUAGE)
2023-03-11 10:30:30 +00:00
if r is None:
return None
2023-03-17 11:30:53 +00:00
llink,lhostname = r
#print(llink,lhostname)
# hostname rules
if not lhostname.endswith(DOMAIN):
LOGGER.debug("bad hostname")
2023-03-11 10:30:30 +00:00
return None
if courlan.is_not_crawlable(llink):
2023-03-12 08:50:22 +00:00
LOGGER.debug("not crawlable")
2023-03-11 10:30:30 +00:00
return None
2023-03-11 13:14:39 +00:00
return llink
2023-03-11 10:30:30 +00:00
2023-03-08 09:56:39 +00:00
def get_link_doc(link,status="frontlink"):
r = courlan.check_url(link)
assert r is not None
2023-03-09 12:29:34 +00:00
link,host = r
2023-03-10 05:23:30 +00:00
domain = courlan.extract_domain(link)
2023-03-12 05:16:47 +00:00
return {"url":link,"host":host,"domain":domain,"status":status,"created_at":datetime.utcnow()}
2023-03-05 17:53:14 +00:00
2023-03-07 15:18:32 +00:00
2023-03-08 09:56:39 +00:00
def fetch_pages(link_batch):
2023-03-07 07:58:28 +00:00
htmls = []
2023-03-11 13:14:39 +00:00
#print(link_batch)
#print("zzzzzzzzzz")
2023-03-07 07:58:28 +00:00
for link in link_batch:
2023-03-08 09:56:39 +00:00
print("fetching:::::")
2023-03-07 15:18:32 +00:00
print(link)
2023-03-11 13:14:39 +00:00
final_link = link
2023-03-11 10:30:30 +00:00
response = trafilatura.fetch_url(link,decode=False)
2023-03-11 13:14:39 +00:00
html = None
if response is not None :
good = True
if response.status != 200:
good = False
2023-03-12 08:50:22 +00:00
LOGGER.error('not a 200 response: %s for URL %s', response.status, url)
2023-03-11 13:14:39 +00:00
elif response.data is None or len(response.data) < MINFILESIZE:
2023-03-25 12:48:38 +00:00
LOGGER.error('too small/incorrect for URL %s', link)
2023-03-11 13:14:39 +00:00
good = False
# raise error instead?
elif len(response.data) > MAXFILESIZE:
good = False
2023-03-25 12:48:38 +00:00
LOGGER.error('too large: length %s for URL %s', len(response.data), link)
2023-03-11 13:14:39 +00:00
if good:
html = trafilatura.utils.decode_response(response)
final_link = response.url
if html is not None:
html, final_link = trafilatura.spider.refresh_detection(html, final_link)
# is there a meta-refresh on the page?
if final_link is None: # malformed or malicious content
html = None
htmls.append((final_link,html))
2023-03-07 15:18:32 +00:00
return htmls
2023-03-07 09:57:47 +00:00
2023-03-11 13:14:39 +00:00
def fetch_robot(base_url):
2023-03-10 12:01:11 +00:00
try:
2023-03-29 08:17:57 +00:00
rawrules = trafilatura.fetch_url("https://"+ base_url + "/robots.txt")
#print(rawrules)
rules = urllib.robotparser.RobotFileParser()
rules.parse(rawrules.split("\n"))
2023-03-14 09:59:58 +00:00
LOGGER.info('got robots')
2023-03-10 12:01:11 +00:00
except Exception as exc:
2023-03-12 08:50:22 +00:00
LOGGER.error('cannot read robots.txt: %s', exc)
2023-03-10 12:01:11 +00:00
rules = None
2023-03-29 08:17:57 +00:00
# exceptions happening here
2023-03-10 15:19:24 +00:00
return rules
2023-03-07 09:57:47 +00:00
2023-03-10 05:23:30 +00:00
def extract_pages(link_batch,responses):
2023-03-07 09:57:47 +00:00
out = []
2023-03-11 13:14:39 +00:00
for original_link,(final_link,html) in zip(link_batch,responses):
2023-03-07 09:57:47 +00:00
doc = None
2023-03-11 13:14:39 +00:00
assert original_link is not None
2023-03-07 09:57:47 +00:00
if html is not None:
2023-03-29 08:17:57 +00:00
doc = trafilatura.bare_extraction(html,url=final_link,with_metadata=True,include_formatting=False,target_language=LANGUAGE,favor_precision=True)
2023-03-12 05:16:47 +00:00
if doc is not None:
if not "text" in doc or len(doc["text"]) < MINTEXTSIZE:
# text too small
doc = None
2023-03-16 15:06:07 +00:00
2023-03-11 13:14:39 +00:00
out.append((original_link,final_link,html,doc))
2023-03-07 09:57:47 +00:00
return out
2023-03-08 09:56:39 +00:00
2023-03-17 11:30:53 +00:00
def index_pages(db,hostname,extracted_pages):
2023-03-07 09:57:47 +00:00
linkcol = db["links"]
htmlcol = db["html"]
2023-03-07 15:18:32 +00:00
contentcol = db["content"]
2023-03-11 13:14:39 +00:00
links = []
2023-03-10 12:01:11 +00:00
for original_link,final_link,html,doc in extracted_pages:
2023-03-07 09:57:47 +00:00
state = "good"
2023-03-12 08:50:22 +00:00
link = original_link
if original_link != final_link:
2023-03-12 09:08:21 +00:00
linkcol.update_one({"url":original_link},{"$set":{"status":"redirect"}})
2023-03-12 08:50:22 +00:00
link = final_link
2023-03-07 09:57:47 +00:00
if html is None:
state = "html_error"
elif doc is None:
state = "content_error"
if doc is not None:
2023-03-14 09:59:58 +00:00
text = doc["text"]
checksums,sizes = calculate_checksums(text)
doc["text_size"] = len(text)
2023-03-07 09:57:47 +00:00
doc["paragraph_checksums"] = checksums
doc["paragraph_sizes"] = sizes
2023-03-29 08:17:57 +00:00
doc["paragraph_sizes_sum"] = sum(sizes)
2023-03-14 09:59:58 +00:00
goodsz = sum(sizes)
2023-03-14 12:54:40 +00:00
if len(text) < 200 or goodsz/len(text) < 0.4:
2023-03-16 15:06:07 +00:00
stat = "trash"
2023-03-12 08:50:22 +00:00
if state == "good":
htdoc = get_link_doc(link,state)
htdoc["html"] = html
htdoc["html_size"] = len(html)
2023-03-14 12:54:40 +00:00
# can be revisited - upsert
del htdoc["url"]
htmlcol.update_one({"url":link},{"$set":htdoc},upsert=True)
2023-03-12 08:50:22 +00:00
doc.update(get_link_doc(link,"good"))
2023-03-10 12:01:11 +00:00
# todo extract links
print(doc)
2023-03-14 12:54:40 +00:00
del doc["url"]
contentcol.update_one({"url":link},{"$set":doc},upsert=True)
2023-03-12 08:50:22 +00:00
linkcol.update_one({"url":original_link},{"$set":{"status":state}})
2023-03-10 15:19:24 +00:00
2023-03-11 10:30:30 +00:00
2023-03-17 11:30:53 +00:00
def extract_links(link_batch,responses,hostname,rules,default_status="frontlink"):
2023-03-11 10:30:30 +00:00
links = {}
2023-03-29 08:17:57 +00:00
badrobot = 0
2023-03-11 13:14:39 +00:00
for original_link,(final_link,html) in zip(link_batch,responses):
2023-03-11 10:30:30 +00:00
status = default_status
2023-03-12 12:53:17 +00:00
external_links = courlan.extract_links(html,final_link,external_bool=True,language=LANGUAGE)
for link in external_links:
links[link] = "frontlink"
2023-03-14 07:59:23 +00:00
internal_links = courlan.extract_links(html,final_link,external_bool=False,language=LANGUAGE)
2023-03-11 13:14:39 +00:00
#print(extracted_links)
2023-03-12 12:53:17 +00:00
for link in internal_links:
2023-03-29 08:17:57 +00:00
if not is_robot_good(link,rules):
badrobot += 1
continue
2023-03-12 12:53:17 +00:00
status = str(default_status)
if courlan.is_navigation_page(link):
2023-03-11 10:30:30 +00:00
status = "navigation"
2023-03-11 13:14:39 +00:00
#print(link,status)
2023-03-11 10:30:30 +00:00
links[link] = status
outlinks = []
2023-03-14 09:59:58 +00:00
badlink = 0
2023-03-11 10:30:30 +00:00
for link,status in links.items():
link = is_link_good(link)
if link is None:
2023-03-14 09:59:58 +00:00
badlink += 1
2023-03-11 10:30:30 +00:00
continue
outlinks.append((link,status))
2023-03-14 09:59:58 +00:00
print(f"{len(links)} total links, {badrobot} badrobot {badlink} badlinks")
2023-03-11 10:30:30 +00:00
return outlinks
def index_links(db,extracted_links):
linkcol=db["links"]
for link,status in extracted_links:
doc = get_link_doc(link,status)
2023-03-12 09:08:21 +00:00
try:
linkcol.insert_one(doc)
except pymongo.errors.DuplicateKeyError as ex:
pass
2023-03-07 09:57:47 +00:00
2023-03-29 08:17:57 +00:00
def get_links(db,hostname,status,batch_size):
2023-03-08 09:56:39 +00:00
linkcol = db["links"]
2023-03-17 11:30:53 +00:00
res = linkcol.find({"status":status,"host":hostname},{"url":1},limit=batch_size)
2023-03-11 13:14:39 +00:00
links = []
2023-03-29 08:17:57 +00:00
for i,doc in enumerate(res):
2023-03-14 12:54:40 +00:00
#print(">>>>>" + status)
2023-03-29 08:17:57 +00:00
#print(doc);
print(">>>>links")
print(doc)
2023-03-11 13:14:39 +00:00
links.append(doc["url"])
2023-03-29 08:17:57 +00:00
if i >= batch_size:
break
2023-03-11 13:14:39 +00:00
return links
2023-03-07 07:58:28 +00:00
2023-03-05 14:44:49 +00:00
2023-03-17 11:30:53 +00:00
def process_links(db,hostname,status,links=[],rules=None,batch_size=BATCHSIZE):
2023-03-11 13:14:39 +00:00
#print(links)
2023-03-11 10:30:30 +00:00
responses = fetch_pages(links)
2023-03-11 13:14:39 +00:00
#print(responses)
2023-03-11 10:30:30 +00:00
extracted_pages = extract_pages(links,responses)
2023-03-11 13:14:39 +00:00
#print(extracted_pages)
2023-03-17 11:30:53 +00:00
extracted_links = extract_links(links,responses,hostname,rules,status)
2023-03-12 12:53:17 +00:00
#print(extracted_links)
2023-03-11 10:30:30 +00:00
index_links(db,extracted_links)
2023-03-17 11:30:53 +00:00
index_pages(db,hostname,extracted_pages)
2023-03-11 10:30:30 +00:00
2023-03-12 05:16:47 +00:00
2023-03-17 11:30:53 +00:00
def link_summary(db,hostname):
2023-03-12 05:16:47 +00:00
linkcol = db["links"]
2023-03-17 11:30:53 +00:00
#res = linkcol.distinct("hostname",{"hostname":hostname})
2023-03-12 08:50:22 +00:00
# count links
2023-03-12 05:16:47 +00:00
res = linkcol.aggregate([
2023-03-17 11:30:53 +00:00
{"$match":{"host":hostname}},
2023-03-12 05:16:47 +00:00
{"$group":{"_id":"$status","count":{"$sum":1}}},
])
for item in res:
print(item)
2023-03-25 13:39:36 +00:00
print(">>>Domain Content")
2023-03-12 08:50:22 +00:00
contentcol = db["content"]
res = contentcol.aggregate([
2023-03-25 13:39:36 +00:00
{"$match":{"host":hostname}},
#{"$project": {"textsum":{"$sum":"$text_size"}}}
2023-03-29 08:17:57 +00:00
{"$group":{"_id":None,
"text_size_sum":{"$sum":"$text_size"},
"paragraph_size_sum":{"$sum":"$paragraph_sizes_sum"}
}
},
2023-03-12 08:50:22 +00:00
])
for item in res:
print(item)
2023-03-12 05:16:47 +00:00
2023-03-12 08:50:22 +00:00
@click.group()
def cli():
pass
@cli.command()
2023-03-12 09:08:21 +00:00
def createdb():
2023-03-12 08:50:22 +00:00
myclient = pymongo.MongoClient(CONNECTION)
db=myclient[DBNAME]
2023-03-12 05:16:47 +00:00
linkcol = db["links"]
2023-03-12 09:08:21 +00:00
linkcol.create_index("url",unique=True)
linkcol.create_index("host")
2023-03-12 05:16:47 +00:00
contentcol = db["content"]
2023-03-12 09:08:21 +00:00
contentcol.create_index("url",unique=True)
#contentcol.create_index({"paragraph_checksums":1})
2023-03-29 08:17:57 +00:00
contentcol.create_index("host")
2023-03-12 05:16:47 +00:00
htmlcol = db["html"]
2023-03-12 09:08:21 +00:00
htmlcol.create_index("url",unique=True)
2023-03-12 05:16:47 +00:00
2023-03-25 12:48:38 +00:00
@cli.command()
@click.argument("link")
def parseurl(link):
2023-03-25 13:39:36 +00:00
link,hostname = courlan.check_url(link)
rawrules = trafilatura.fetch_url("https://"+ hostname + "/robots.txt")
print(rawrules)
rules = urllib.robotparser.RobotFileParser()
rules.parse(rawrules.split("\n"))
print(rules.can_fetch("*",link))
print(rules.site_maps())
print(rules.crawl_delay("*"))
2023-03-25 12:48:38 +00:00
html = trafilatura.fetch_url(link,decode=True)
doc = trafilatura.bare_extraction(html)
import pprint
pprint.pprint(doc)
@cli.command()
@click.argument("link")
def externaldomains(link):
html = trafilatura.fetch_url(link,decode=True)
external_links = courlan.extract_links(html,link,external_bool=True,language=LANGUAGE)
domains = set()
for l in external_links:
r = courlan.check_url(l)
if r is None:
pass
link,domain = r
domains.add(domain)
for d in domains:
print(d)
2023-03-16 15:06:07 +00:00
2023-03-12 08:50:22 +00:00
@cli.command()
2023-03-12 05:56:08 +00:00
@click.argument("start_link")
2023-03-12 08:50:22 +00:00
def visit(start_link):
myclient = pymongo.MongoClient(CONNECTION)
db=myclient[DBNAME]
2023-03-17 11:30:53 +00:00
start_link,hostname = courlan.check_url(start_link)
rules = fetch_robot(hostname)
2023-03-12 08:50:22 +00:00
print(rules)
2023-03-11 17:41:20 +00:00
batch_size = BATCHSIZE
2023-03-17 11:30:53 +00:00
navigation_links = get_links(db,hostname,"navigation",batch_size)
2023-03-11 17:41:20 +00:00
if start_link is not None:
navigation_links.append(start_link)
2023-03-14 07:59:23 +00:00
print(f"Navigation links {len(navigation_links)}")
2023-03-17 11:30:53 +00:00
process_links(db,hostname,"frontlink",navigation_links,rules)
links = get_links(db,hostname,"frontlink",batch_size)
2023-03-11 17:41:20 +00:00
bl = len(links) - batch_size
2023-03-14 07:59:23 +00:00
print(f"Got {len(links)} frontlinks")
2023-03-11 17:41:20 +00:00
if bl > 0:
print("Getting backlinks")
2023-03-17 11:30:53 +00:00
front_links = get_links(db,hostname,"backlink",bl)
2023-03-12 12:53:17 +00:00
links += front_links
2023-03-14 07:59:23 +00:00
print("Processing backlinks")
2023-03-17 11:30:53 +00:00
process_links(db,hostname,"backlink",links,rules=rules)
link_summary(db,hostname)
2023-03-12 05:56:08 +00:00
if __name__ == "__main__":
cli()