Random Word from Website - python-2.7

I have a simple program (not related to school) that requires a lot of random words in the local database. Earlier today, I found this website http://www.setgetgo.com/randomword/get.php that will always generate a random word every time the page is reloaded. I have an idea to create a variable that will consistently grab the value from this website, and append it to my list (acts as a local database).
Any idea how to do that? I thought there is a "wget" library in python too. However, my python keeps returning an error.
My idea:
a_variable = wget the website text

Here is the block of code you need
import requests
res = requests.get("http://www.setgetgo.com/randomword/get.php")
print res.content
I would adivce you to dive into Request and BeautifulSoup. If you want to learn more about it.
Goodluck

Related

How do I get all cookies from a site, including 3rd party?

I've been asked to write a web crawler that lists all cookies (including 3rd party such as Youtube) and then checks them in a database that provides extra info (such as what is the cookie for). Users write their address in a search bar and then receive the info.
The problem is: I'm completly lost! I barely have any idea where to begin from, what to do, and it's starting to give me actual headaches.
I can think up the logic, and I know it shouldn't be a hard problem, but what do I have to use?
I have tried Selenium (still have no idea how it works) with Python mainly, I've looked at Java and even considered C#, but still, the problem is that I don't know where to start this from, what to use to do it. Every step I take is like climbing a wall, only to drop on the other side and find a larger wall.
All I ask is some guidance, no need for actual code.
Alright so I finally got something going. The trick is Python + Selenium + ChromeDriver. I will post more details in the future once I get this all done.
With Python 3, this is enough to connect to a site and get an output of cookies (they're, in this case, stored in myuserdir/Documents/Default/cookies):
from selenium import webdriver
import sys
co = webdriver.ChromeOptions()
co.add_argument("user-data-dir={}".format("C:\\Users\\myuserdir\\Documents"))
driver = webdriver.Chrome(chrome_options = co)
driver.get("http://www.example.com)
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
def getCookies(self):
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'./geckodriver')
driver.get(self.website_url)
cookie = driver.get_cookies()
driver.quit()
return cookie
The approach I used is use get_cookies() to store cookie file for future use. But sometimes you need to simulate js process to get cookies loaded by javascript code.

From local scrapy to scrapy cloud (scraping hub) - Unexpected results

The scraper I deployed on Scrapy cloud is producing an unexpected result compared to the local version.
My local version can easily extract every field of a product item (from an online retailer) but on the scrapy cloud, the field "ingredients" and the field "list of prices" are always displayed as empty.
You'll see in a picture attached the two elements I'm always having empty as a result whereas it's perfectly working
I'mu using Python 3 and the stack was configured with a scrapy:1.3-py3 configuration.
I thought first it was in a issue with the regex and unicode but seems not.
So i tried everything : ur, ur RE.ENCODE .... and didn't work.
For the ingredients part, my code is the following :
data_box=response.xpath('//*[#id="ingredients"]').css('div.information__tab__content *::text').extract()
data_inter=''.join(data_box).strip()
match1=re.search(r'([Ii]ngr[ée]dients\s*\:{0,1})\s*(.*)\.*',data_inter)
match2=re.search(r'([Cc]omposition\s*\:{0,1})\s*(.*)\.*',data_inter)
if match1:
result_matching_ingredients=match1.group(1,2)[1].replace('"','').replace(".","").replace(";",",").strip()
elif match2 :
result_matching_ingredients=match2.group(1,2)[1].replace('"','').replace(".","").replace(";",",").strip()
else:
result_matching_ingredients=''
ingredients=result_matching_ingredients
It seems that the matching never occurs on scrapy cloud.
For prices, my code is the following :
list_prices=[]
for package in list_packaging :
tonnage=package.css('div.product__varianttitle::text').extract_first().strip()
prix_inter=(''.join(package.css('span.product__smallprice__text').re(r'\(\s*\d+\,\d*\s*€\s*\/\s*kg\)')))
prix=prix_inter.replace("(","").replace(")","").replace("/","").replace("€","").replace("kg","").replace(",",".").strip()
list_prices.append(prix)
That's the same story. Still empty.
I repeat : it's working fine on my local version.
Those two data are the only one causing issue : i'm extracting a bunch of other data (with Regex too) with scrapy cloud and I'm very satisfied with it ?
Any ideas guys ?
I work really often with ScrapingHub, and usually the way I do to debug is:
Check the job requests (through the ScrapingHub interface)
In order to check if there is not a redirection which makes the page slightly different, like a query string ?lang=en
Check the job logs (through the ScrapingHub interface)
You can either print or use a logger to check everything you want trough your parser. So if you really want to be sure the scraper display the same on local machine and on ScrapingHub, you can print(response.body) and compare what might cause this difference.
If you can not find, I'll try to deploy a little spider on ScrapingHub and edit this post if I can manage to have some time left today !
Check that Scrapping Hub’s logs are displaying the expected version of Python even if the stack is correctly set up in the project’s yml file.

How can I improve this piece of code (scraping with Python)?

I'm quite new to programming so I appologise if my question is too trivial.
I've recently taken some Udacity courses like "Intro to Computer Science", "Programming foundations with Python" and some others.
The other day my boss asked me to collect some email addresses from certain websites. Some of them had many addresses at the same page so, the bell rang and I was thinking of creating my own code to do the repetitive task of collecting the emails and pasting them in a spreadsheet.
So, after reviewing some of the lessons of those corses plus some videos on youtube I came up with this code.
Notes: It's written in Python 2.7.12 and I'm using Ubuntu 16.04.
import xlwt
from bs4 import BeautifulSoup
import urllib2
def emails_page2excel(url):
# Create html file from a given url
sauce = urllib2.urlopen(url).read()
soup = BeautifulSoup(sauce,'lxml')
# Create the spreadsheet book and a page in it
wb = xlwt.Workbook()
sheet1 = wb.add_sheet('Contacts')
# Find the emails and write them in the spreadsheet table
count = 0
for url in soup.find_all('a'):
link = url.get('href')
if link.find('mailto')!=-1:
start_email = link.find('mailto')+len('mailto:')
email = link[start_email:]
sheet1.write(count,0,email)
count += 1
wb.save('This is an example.xls')
The code runs fine and it's quite quick. However I'd like to improve it in these ways:
I got the feeling that the for loop could be done in a more elegant
way. Is there any other way to look for the email besides the string find? Just in a similar way in which I found the 'a' tags?
I'd like to be able to evaluate this code with a list of websites(most likely in a spreadsheet) instead of evaluating it only with a url string. I haven't had time to research on how to do this yet but any suggestion is welcome.
Last but not least, I'd like to ask if there's any way to implement this script in some sort of friendly-to-use mini-programme. I mean, for instance, my boss is totally bad at computers: I can't imagine her opening a terminal shell and executing the python code. Instead I'd like to crate some programme where she could just paste the url, or upload a spreadsheet with the websites she wants to extract the emails from, select whether she wants to extract emails or any other information, maybe some more features and then click a button and get the result.
I hope I've expressed myself clearly.
Thanks in advance,
Anqin
As far as BeautifulSoup goes you can search for emails in a in three ways:
1) Use find_all with a lambda to search all tags that are a and have href as an attribute and its value has mailto.
for email in soup.find_all(lambda tag: tag.name == "a" and "href" in tag.attrs and "mailto:" in tag.attrs["href"]):
print (email["href"][7:])
2) Use find_all with regex to find mailto: in an a tag.
for email in soup.find_all("a", href=re.compile("mailto:")):
print (email["href"][7:])
3) Use select to find an a tag on which its href attribute starts with mailto:.
for email in soup.select('a[href^=mailto]'):
print (email["href"][7:])
This is my personal preference, but I prefer using requests over urllib. Far simpler, better at error handling and safer when threading.
As far as your other questions, you can create a method for fetching, parsing and returning the results that you want and pass an url as a parameter. You would only need to loop your list of urls and call that method.
For your boss question you should use a GUI.
Have fun coding.

How to create separate python script for uploading data into ndb

Can anyone guide me towards the right direction as to where I should place a script solely for loading data into ndb. As I wish to upload all data into the gae ndb so that the application could perform query on it.
Right now, the loading of data is in my application. I wish to placed it separately from the main application.
Should it be edited in the yaml file?
EDITED
This is a snippet of the entity and the handler to upload the data into GAE ndb.
I wish to placed this chunk of code separately from my main application .py. Reason being the uploading of this data won't be done frequently and to keep the codes in the main application "cleaner".
class TagTrend_refine(ndb.Model):
tag = ndb.StringProperty()
trendData = ndb.BlobProperty(compressed=True)
class MigrateData(webapp2.RequestHandler):
def get(self):
listOfEntities = []
f = open("tagTrend_refine.txt")
lines = f.readlines()
f.close()
for line in lines:
temp = line.strip().split("\t")
data = TagTrend_refine(
tag = temp[0],
trendData = temp[1]
)
listOfEntities.append(data)
ndb.put_multi(listOfEntities)
For example if I placed the above code in a file called dataLoader.py, where should I call this script to invoke?
In app.yaml alongside my main application(knowledgeGraph.application)?
- url: /.*
script: knowledgeGraph.application
You don't show us the application object (no doubt a WSGI app) in your knowledge.py module, so I can't know what URL you want to serve with the MigrateData handler -- I'll just guess it's something like /migratedata.
So the class TagTrend_refine should be in a separate file (usually called models.py) so that both your dataloader.py, and your knowledge.py, can import models to access it (and models.py will need its own import of ndb of course). (Then of course access to the entity class will be as models.TagTrend_refine -- very basic Python).
Next, you'll complete dataloader.py by defining a WSGI app, e.g, at end of file,
app = webapp2.WSGIApplication(routes=[('/migratedata', MigrateData)])
(of course this means this module will need to import webapp2 as well -- can I take for granted a knowledge of super-elementary Python?).
In app.yaml, as the first URL, before that /.*, you'll have:
url: /migratedata
script: dataloader.app
Given all this, when you visit '/migratedata', your handler will read the "tagTrend_refine.txt" file that you uploaded together with your .py, .yaml, and so on, files in your overall GAE application, and unconditionally create one entity per line of that file (assuming you fix the multiple indentation problems in your code as displayed above, but, again, this is just super-elementary Python -- presumably you've used both tabs and spaces and they show up OK in your editor, but not here on SO... I recommend you use strictly, only spaces, never tabs, in Python code).
However this does seem to be a peculiar task. If /migratedata gets visited twice, it will create duplicates of all entities. If you change the tagTrend_refine.txt and deploy a changed variation, then visit /migratedata... all old entities will stick around and all the new entities will join them. And so forth.
Moreover -- /migratedata is NOT idempotent (if visited more than once it does not produce the same state as running it just once) so it shouldn't be a GET (and now we're on to super-elementary HTTP for a change!-) -- it should be a POST.
In fact I suspect (but I'm really flying blind here, since you see fit to give such tiny amounts of information) that you in fact want to upload a .txt file to a POST handler and do the updates that way (perhaps avoiding duplicates...?). However, I'm no mind reader, so this is about as far as I can go.
I believe I have fully answered the question you posted (though perhaps not the one you meant but didn't express:-) and by SO's etiquette it would be nice to upvote and accept this answer, then, if needed, post another question, expressing MUCH more clearly and completely what you're trying to achieve, your current .py and .yaml (ideally with correct indentation), what they actually do and why you'd like to do something different. For POST vs GET in particular, just study When should I use GET or POST method? What's the difference between them? ...
Alex's solution will work, as long as all you data can be loaded in under 1 minute, as that's the timeout for an app engine request.
For larger data, consider calling the datastore API directly from your own computer where you have the source. It's a bit of a hassle because it's a different API; it's not ndb. But it's still a pretty simple API. Here's some code that calls the API:
https://github.com/GoogleCloudPlatform/getting-started-python/blob/master/2-structured-data/bookshelf/model_datastore.py
Again, this code can run anywhere. It doesn't need to be uploaded to app engine to run.

i need to restart django server to make my app properly work

so i made a python script to grab images from a subreddit (from Imgur and imgur albums). i successfully done that (it returns img urls) and wanted to integrate it into django so i can deploy it online and let other people use it. when i started running the server at my machine, the images from subreddit loads flawlessly, but when i try another subreddit, it craps out on me (i'll post the exception at the end of the post). so i restart the django server, and same thing happen. the images loads without a hitch. but the second time i do it, it craps out on me. what gives?
Exception Type: siteError, which pretty much encompasses urllib2.HTTPError, urllib2.URLError, socket.error, socket.sslerror
since i'm a noob in all of this, i'm not sure what's going on. so anyone care to help me?
note: l also host the app on pythoneverywhere.com. same result.
Using a global in your get_subreddit function looks wrong to me.
reddit_url = 'http://reddit.com/r/'
def get_subreddit(name):
global reddit_url
reddit_url += name
Every time, you run that function, you append the value of name to a global reddit_url.
It starts as http://reddit.com/r/
run get_subreddit("python") and it changes to http://reddit.com/r/python
run get_subreddit("python") again, and it changes to http://reddit.com/r/pythonpython
at this point, the url is invalid, and you have to restart your server.
You probably want to change get_subreddit so that it returns a url, and fetch this url in your function.
def get_subreddit(name):
return "http://reddit.com/r/" + name
# in your view
url = get_subreddit("python")
# now fetch url
There are probably other mistakes in your code as well. You can't really expect somebody on stack overflow to fix all the problems for you on a project of this size. The best thing you can do is learn some techniques for debugging your code yourself.
Look at the full traceback, not just the final SiteError. See what line of your code the problem is occurring in.
Add some logging or print statement, and try and work out why the SiteError is occurring.
Are you trying to download the url that you think you are (as I explained above, I don't think you are, because of problems with your get_subreddit method).
Finally, I recommend you make sure that the site works on your dev machine before you move on to deploying it on python anywhere. Deploying can cause lots of headaches all by itself, so it's good to start with an app that's working before you start.
Good luck :)