repl.it
@Scoder12/

imdb scrape

Python

No description

fork
loading
Files
  • main.py
  • descriptions.txt
  • next_url.txt
  • poetry.lock
  • pyproject.toml
  • requirements.txt
  • titles_old.csv
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import replit; replit.clear()
import requests
from bs4 import BeautifulSoup as Bs
from imdb import IMDb
import traceback
import tqdm

imdb = IMDb()
l = 'https://www.imdb.com/search/title/?title_type=feature&genres=action&explore=genres&ref_=adv_nxt'

print("reading file...")
def count_lines():
    lines = 0
    with open("descriptions.txt", "r") as f:
        for line in f.readlines():
            if line.strip():
                lines += 1
    return lines

amnt = count_lines()

if amnt != 0:
    checked = False
    try:
        with open("next_url.txt", "r") as f:
            done, nextl = f.readlines()
        done = int(done)
        #print(amnt, done, nextl)
        
        if amnt == done:
            print(f"next_url.txt success, {amnt} == {done}, nextl = {nextl}")
            l = nextl
            checked = True
        elif amnt > done:
            print(f"clipping, next_url.txt {amnt} < {done}, nextl = {nextl}")
            with open("descriptions.txt", "r") as f:
                descs = [i for i in f.readlines() if i]
            descs = descs[:done]
            with open("descriptions.txt", "w+") as f:
                for d in descs:
                    f.write(str(d) + "\n")
            checked = True
            
    except:
        traceback.print_exc()
    
    if not checked:
        print("clearing file...")
        with open("descriptions.txt", "w+") as f:
            f.write("")
    

def one_ele_list(l):
    if len(l) != 1:
        raise ValueError(f"list is not 1 element: {l}")
    return l[0]


def get_movie_ids(url):
    #print(f"Requesting...")
    r = requests.get(url)
    if r.status_code != 200:
        print("no good")
        return []
    html = r.text
    #print("Parsing...")
    soup = Bs(html, 'html.parser')
    def check(tag):
        return 'lister-item-header' in tag.parent.attrs.get('class', [])
    link = soup.find("a", {'class': "lister-page-next next-page"})
    assert link
    link = link.attrs['href']
    if link.startswith("/"):
        link = "https://www.imdb.com" + link
    title_eles = soup.find_all(check)

    mids = []

    for t in title_eles:
        if t.name != 'a':
            continue
        url = t.attrs.get('href')
        # usually in format of /title/tt123456789
        if url:
            parts = [i for i in url.split('/') if i]
            if len(parts) >= 2 and parts[1].startswith('tt'):
                mids.append(parts[1][2:]) # remove tt

    return mids, link

def get_synopsis(mid):
    r = requests.get(f'https://imdb.com/title/tt{mid}')
    if r.status_code != 200:
        print(f"no good {r.status_code}")
        return ''
    soup = Bs(r.text, 'html.parser')
    s = soup.find('div', {'class': 'summary_text'})
    if not s:
        return ''
    return s.get_text().strip()


#links = ['https://www.imdb.com/search/title/?genres=action&title_type=feature&explore=genres']



def progress(amnt, total=50):
    if amnt < 0:
        raise ValueError("amnt must be at least 0")
    if total < 1:
        raise ValueError("total must be at least 1")
    #if amnt > total:
    #    raise ValueError("amnt cannot be more than total")
    digits = len(str(total))
    samnt = str(amnt).zfill(digits)
    stotal = str(total).zfill(digits)

    arrow = 1 if amnt else 0
    eq = min([amnt - 1, total - 1])
    spaces = total - min([amnt, total])
    print(f"\r{samnt}/{stotal} [{'='*eq}{'>' * arrow}{' ' * spaces}]", end='')

descriptions = []

print("starting...")
try:
    while True:
        oldamnt = len(descriptions)
        mids, l = get_movie_ids(l)
        print("Got ids. ")
        if not l:
            break
        done = 0
        #progress(0, total=len(mids))
        for m in tqdm.tqdm(mids):
            try:
                r = imdb.get_movie_synopsis(m)
                # ends with ::author name, so we remove it
                desc = r['data']['plot'][0].split("::")[0]
                descriptions.append(desc)
            except:
                print('bad mid: {m}')
                traceback.print_exc()
            done += 1
            #progress(done, total=len(mids))

        with open("descriptions.txt", "a") as f:
            for t in descriptions:
                f.write(str(t) + "\n")
        amnt = count_lines()            
        with open("next_url.txt", "w+") as f:
            f.write(str(amnt) + "\n" + l)
        added = len(descriptions) - oldamnt
        descriptions = []
        print(f"added {added}, {len(descriptions)} descs, ({amnt} saved) next url {l}")
            
except NotImplementedError:
    print("stopping parse")


print("writing...")
with open("titles.csv", "a") as f:
    for t in descriptions:
        f.write(t)