Go Back   CodingForums.com > :: Server side development > Other server side languages/ issues > Python

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-09-2011, 12:51 AM   PM User | #1
MetalMichael
New Coder

 
Join Date: Aug 2010
Posts: 27
Thanks: 4
Thanked 0 Times in 0 Posts
MetalMichael is an unknown quantity at this point
Open url to perform operations

Okay, well I'm pretty new to python. I can open a url, but when it comes to doing anything with it, I keep getting errors. Pretty sure I'm doing it wrong.

So I've imported urllib.request, and do:
youtubesearch = urllib.request.urlopen('http://www.youtube.com/results?search_query=' + query)

this opening works, but then when I want to do something with it, for example, perform regex operations, I the error TypeError: expected string or buffer.
code used:
youtubere = re.compile('watch\?v=([^\"&]+)"\stitle[\s\S]{0,400}?<b>' + query, re.I)
youtubesearch = urllib.request.urlopen('http://www.youtube.com/results?search_query=' + query)
youtubelink = re.search(youtubere, youtubesearch)
Full error:
(other traces)
File "C:\Python31\lib\re.py", line 157, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer

Edit: Note, using python 3.1

Just for note... this is the sort of thing that if I were using php, I would do
$page = file_get_contents($Url);
preg_match('/regex\sand\sstuff/i',$page,$output)

Last edited by MetalMichael; 01-09-2011 at 12:52 AM.. Reason: adding 3.1 note
MetalMichael is offline   Reply With Quote
Old 01-09-2011, 11:44 AM   PM User | #2
Kakao
Regular Coder

 
Join Date: Mar 2006
Location: Brasília, Brazil
Posts: 153
Thanks: 0
Thanked 0 Times in 0 Posts
Kakao is on a distinguished road
urllib.request.urlopen returns a file like object so you need to use the read method of a file like object:

Code:
youtubelink = re.search(youtubere, youtubesearch.read())
Kakao is offline   Reply With Quote
Old 01-09-2011, 04:33 PM   PM User | #3
MetalMichael
New Coder

 
Join Date: Aug 2010
Posts: 27
Thanks: 4
Thanked 0 Times in 0 Posts
MetalMichael is an unknown quantity at this point
Ah, thanks, still thinking in a non python mind-set...

However, when I try this, I get the error:
TypeError: can't use a string pattern on a bytes-like object



edit: thanks, works when I use
Code:
youtubelink = re.search(youtubere, youtubesearch.read().decode('utf-8')

Last edited by MetalMichael; 01-09-2011 at 04:39 PM..
MetalMichael is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 05:23 AM.


Advertisement
Log in to turn off these ads.