Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- from bs4 import BeautifulSoup
- import csv
- def load_id_dict(): ## renamed to dict, more common abbreviation
- with open('strings.csv', 'r', newline='') as f:
- file_data = csv.reader(f, delimiter=',') ## renamed so we aren't reusing names (i.e. reader), even though technically they wouldn't conflict
- id_dic = {row[0]: (row[1]) for row in file_data}
- return id_dic
- ## moved headers outside loop, doesn't need to be initialized every time
- headers = {
- "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
- workingString = ""
- for _, v in load_id_dict().items(): ## k isn't currently used, so use _ instead, but we still have the option to use it later if we want to
- URL = 'http://poe.trade/search/' + v ## removed redundant brackets
- page = requests.get(URL, headers=headers)
- soup = BeautifulSoup(page.content, 'html.parser')
- item_name = soup.findAll("tbody", {"id": "item-container-0"})
- item_prices = soup.findAll("span", {"class": "currency"})
- title = item_name[0]["data-name"] ## no need to loop over all the items, they should all
- ## have the same name, so just use the first one
- prices = []
- ## removed foundChaos
- for container in item_prices[:5]:
- price = container["title"] ## moved this statement to before the if
- if "chaos" in price: ## simplified
- price = price.replace(' chaos', '')
- price = int(price)
- prices.append(price)
- avgPrice = sum(prices) / len(prices) if prices else "N/A" ## make sure prices isn't empty
- ## use += instead of =
- ## workingString += title + "," + str(avgPrice) + "\n"
- ## but also use f-strings
- workingString += f"{title},{avgPrice}\n"
- print(workingString)
- filename = "out.csv"
- with open(filename, "w") as output_file:
- output_file.write(workingString)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement