I'm trying to use spynner to auto-click some button in the HTML source code as a small test. But I'm receiving this error.
Traceback (most recent call last):
File "build\bdist.win32\egg\spynner\browser.py", line 287, in _on_reply
AttributeError: 'Browser' object has no attribute 'manager'
Below is my code, which is following the guide here:https://github.com/makinacorpus/spynner/blob/master/examples/webkit_methods.py
import spynner
import libxml2
proxy_ip = "xxx.xxx.xxx.xxx";
browser = spynner.Browser()
# setting proxy ip
browser.set_proxy(proxy_ip :'8080');
browser.show()
try:
browser.load(url='http://xxx.html', load_timeout=10, tries=1)
except spynner.SpynnerTimeout:
print 'Timeout.'
else:
browser.wk_click('a[id="voteProjectBtn_10353150"]', wait_load=True)
browser.close()
I'm using Python 2.7, thanks for the help!
before browser.close(), you must distroy the loop javascript, some website has timming script, so you need distroy these script
see the browser.py, change the method "_manager_create_request" ,
before browser.close(), set self.closeflag = True
def _manager_create_request(self, operation, request, data):
if self.closeflag:
return None
url = unicode(request.url().toString())
operation_name = self._operation_names[operation].upper()
self._debug(INFO, "Request: %s %s" % (operation_name, url))
for h in request.rawHeaderList():
self._debug(DEBUG, " %s: %s" % (h, request.rawHeader(h)))
if self._url_filter:
if self._url_filter(self._operation_names[operation], url) is False:
self._debug(INFO, "URL filtered: %s" % url)
request.setUrl(QUrl("about:blank"))
else:
self._debug(DEBUG, "URL not filtered: %s" % url)
reply = QNetworkAccessManager.createRequest(self.manager,
operation, request, data)
return reply
Related
I'm trying to run this Telegram image downloader:
https://github.com/fabifrank/telegram-image-downloader
When I run it I get an error:
AttributeError: 'MessageMediaPhoto' object has no attribute 'document'
The code looks like this:
if(debug_enabled):
print(update)
if update.message.media is not None:
file_name = 'unknown name';
attributes = update.message.media.document.attributes
for attr in attributes:
if isinstance(attr, types.DocumentAttributeFilename):
file_name = attr.file_name
print("[%s] Download queued at %s" % (file_name, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
message = await update.reply('In queue')
await queue.put([update, message])
I'm using Python 3.10
That's because MessageMediaPhoto does not have document but MessageMediaDocument has. I had the same issue and I used continue to skip through the exception.
async for message in takeout.iter_messages(channel, wait_time=0):
try:
print(message.media.document)
except:
continue
This will print out the document name if there is any otherwise it will show nothing. Hope it helps!
For those of you who have experience with Strava API - I used the documentation on their developer site: https://developers.strava.com/docs/reference/#api-Activities-getLoggedInAthleteActivities
However, copying their code over I get an attribute error-
AttributeError: 'ActivitiesApi' object has no attribute 'getActivityById'
AttributeError: 'ActivitiesApi' object has no attribute 'getLoggedInAthleteActivities'
Any idea why? Obviously inputted my ID/secret/token as from their website. Code below:
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint
STRAVA_CLIENT_ID = MY_CLIENT_ID
STRAVA_CLIENT_SECRET = 'MY_CLIENT_SECRET'
STRAVA_ACCESS_TOKEN = 'MY_ACCESS_TOKEN'
swagger_client.configuration.access_token = STRAVA_ACCESS_TOKEN
api_instance = swagger_client.ActivitiesApi()
def get_activity_data():
activity_id = 3307145226
includeAllEfforts = True # Boolean | To include all segments efforts. (optional)
try:
# Get Activity
api_response = api_instance.getActivityById(id,
includeAllEfforts=includeAllEfforts)
pprint(api_response)
except ApiException as e:
print("Exception when calling ActivitiesApi->getActivityById: %s\n" % e)
return
Looks like you have an error for passing the id to getActivityById. Your activity id variable is activity_id but you're passing in id. Not sure if that will fix your issue or not but it's a start.
I am trying scrape with BS4 via TOR, using the To Russia With Love tutorial from the Stem project.
I've rewritten the code a bit, using i.a. this answer, and it now looks like this,
SOCKS_PORT=7000
def query(url):
output = io.BytesIO()
query = pycurl.Curl()
query.setopt(pycurl.URL, url)
query.setopt(pycurl.PROXY, 'localhost')
query.setopt(pycurl.PROXYPORT, SOCKS_PORT)
query.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5_HOSTNAME)
query.setopt(pycurl.WRITEFUNCTION, output.write)
try:
query.perform()
return output.getvalue()
except pycurl.error as exc:
return "Unable to reach %s (%s)" % (url, exc)
def print_bootstrap_lines(line):
if "Bootstrapped " in line:
print(term.format(line, term.Color.BLUE))
print(term.format("Starting Tor:\n", term.Attr.BOLD))
tor_process = stem.process.launch_tor_with_config(
tor_cmd = '/Applications/TorBrowser.app/Contents/MacOS/Tor/tor.real',
config = {
'SocksPort': str(SOCKS_PORT),
'ExitNodes': '{ru}',
'GeoIPFile': r'/Applications/TorBrowser.app/Contents/Resources/TorBrowser/Tor/geoip',
'GeoIPv6File' : r'/Applications/TorBrowser.app/Contents/Resources/TorBrowser/Tor/geoip6'
},
init_msg_handler = print_bootstrap_lines,
)
print(term.format("\nChecking our endpoint:\n", term.Attr.BOLD))
print(term.format(query("https://www.atagar.com/echo.php"), term.Color.BLUE))
I am able to Establish a Tor circuit, but at "checking our endpoint", I receive a the following error,
Checking our endpoint:
Traceback (most recent call last):
File "<ipython-input-804-68f8df2c050b>", line 40, in <module>
print(term.format(query('https://www.atagar.com/echo.php'), term.Color.BLUE))
File "/Applications/anaconda/lib/python3.6/site-packages/stem/util/term.py", line 139, in format
if RESET in msg:
TypeError: a bytes-like object is required, not 'str'
What should I change to see the endpoint?
I've temporarily solved it by changing the last line of the above code with,
test=requests.get('https://www.atagar.com/echo.php')
soup = BeautifulSoup(test.content, 'html.parser')
print(soup)
but I'd like to know how to get the 'original' line working.
You must be using Python 3, when that code was made for Python 2. In Python 2, str and bytes are the same thing, and in Python 3, str is Python 2's unicode. You have to add a b directly before the string to make it a byte string in Python 3, e.g.:
b"this is a byte string"
I am trying to verify some text e.g. "test001" on a webpage using driver.getPageSource in Python, Webdriver.
I get the error object has no attribute 'getPageSource':
Traceback (most recent call last):
File "C:\Users\riaz.ladhani\PycharmProjects\Selenium Webdriver\ClearCore \TestCases\AdministrationPage_TestCase.py", line 32, in test_add_Project
administration_page.add_project()
File "C:\Users\riaz.ladhani\PycharmProjects\Selenium Webdriver\ClearCore \Pages\admin.py", line 43, in add_project
test = self.driver.getPageSource
AttributeError: 'WebDriver' object has no attribute 'getPageSource'
Having looked at other people's posts with similar issues. They replies are to use getPageSource.
I'm not sure why I am getting the error. Some help appreciated, thanks.
My code snippet is:
class AdministrationPage(BasePage):
def is_project_text_present(self, text):
#return str(text) in self.driver.getPageSource
try:
project_list_test = self.driver.getPageSource
except NoSuchElementException, e:
return False
return "test001" in text # check if the project title text test001 is in the page, return true if it is
class AdministrationPage_TestCase(unittest.TestCase):
try: administration_page.is_text_present("test001")
except AssertionError as e: self.verificationErrors.append(str(e))
Seems like a syntax error to me it should be page_source not getPageSource. See the doc
Try
def is_project_text_present(self, text):
#return str(text) in self.driver.page_source
try:
project_list_test = self.driver.page_source
except NoSuchElementException, e:
return False
return "test001" in text # check if the project title text test001 is in the page, return true if it is
However, grabbing the full page source to test a single text is not a good idea I think. Just find the intended element and test if the element contains the text you are looking for instead
I am utterly lost at what should be an easy task.
I am trying to use Python with SUDS to grab a WSDL URL, create client objects, modify some information, and then post back up the WSDL (Or where ever it tell me to post it).
I get the following error message:
Traceback (most recent call last):
File "./test.py", line 47, in <module>
email_sent = client.service.sendEmail(From, SenderContext, Email)
NameError: name 'client' is not defined
If I remove the "Try:" section in the code and insert come print code to print the objects, everything works just fine. It does grab the information and do the changes I want.
What I don't understand is that the client object is created and I am trying to post the information back up, but can't. Any one have any experience with XML and Python?
import sys
import logging
import traceback as tb
import suds.metrics as metrics
import unittest
from suds import null, WebFault
from suds.client import Client
def sendTestMail():
url = 'wsdl url at my company'
client = Client(url)
SenderContext = client.factory.create('senderContext')
SenderContext.registeredSenderId = 'Endurance'
SenderContext.mailType = 'TRANSACTIONAL_OTHER'
SenderContext.subSenderId = 12345
From = client.factory.create('emailAddressBean')
From.address = 'me#somecompany.com'
From.valid = 'TRUE'
Email = client.factory.create('email')
Email.recipients = 'me#somecompany.com'
Email.ccRecipients = ''
Email.bccRecipients = ''
Email.agencyId = ''
Email.content = 'This is a test of sending'
Email.contentType = 'text/plain'
Email.description = ''
#Email.from = From
Email.fromName = 'An Employee'
Email.subject = 'This is a test'
Email.mrrId = ''
Email.templateId = ''
try:
email_sent = client.service.sendEmail(From, SenderContext, Email)
except WebFault, e:
print e
if __name__ == '__main__':
errors = 0
sendTestMail()
print '\nFinished: errors=%d' % errors
You define client in the sendTestMail() class, but then use a lower-level indentation in your try/except statement. Therefore, client is not within scope at this point. Either indent your try/except block to be within the sendTestMail() scope or declare client globally.