Ta kontakt med oss

MARKNADSFÖRING

10 sätt att använda AI för bättre annonser

Publicerad

10 sätt att använda AI för bättre annonser

In our recent post about OpenAI’s ChatGPT, we unpacked what the tool is and how it works, and why we don’t see its popularity as a threat to search engines like Google. In this post, we’ll be diving further into the OpenAI Playground, and how PPC marketers can use that tool along with ChatGPT to save time on research, ideation, execution, and more.

The Playground is a basic UI built on top of OpenAI’s API. OpenAI has recently added ChatGPT to their API. When accessing ChatGPT through this UI, users have the ability to customize the model being used for each query (or continuation of the “conversation”) as they progress through their work.
 

How to Write ChatGPT Prompts

 
When working with tools like ChatGPT, it’s important to be as clear as possible in what you ask, and how you ask it. As you write prompts for ChatGPT to work with in retrieving and displaying the information you need, remember that you are giving instructions in a more direct way than you might if conversing with a colleague.

While another person may have contextual insight into what you’re verkligen looking for with your question, tools like ChatGPT take language more literally, tailoring their response to the information you explicitly provide in your request.

ChatGPT will consider every element of your ask, so don’t give generic prompts. The more information you provide the tool in your prompt, the better it will be able to generate what you’re looking for in its response.

Example: Let’s assume you’re using ChatGPT for dinner inspiration…

  • Generic prompt (least likely to return what you’re looking for): Give me 10 recipe ideas for a home-cooked dinner
  •  

  • Slightly better prompt: Give me 10 recipe ideas for a home-cooked dinner with squash as the primary ingredient
  •  

  • Even better prompt: Give me 10 recipe ideas for a vegetarian home-cooked dinner that I can make in an air fryer in 20 minutes or less with squash as the primary ingredient

See här and the examples below for more information and inspiration on crafting strong prompts.
 

How to Start Using the OpenAI Playground for PPC Marketing

 

To get started with the OpenAI Playground, create an account using your personal email address at https://platform.openai.com/. Once you’re logged in, navigate to the Playground page to access the interface and begin making requests.

skärmdump av öppen lekplats

The right-hand sidebar provides some options for different modes and GPT submodels, as well as Codex models, which are primarily used for generating code. The Complete mode is selected by default, along with the text-davinci-003 model. The other models within the “Complete” mode are typically faster and cheaper but are also less advanced, so they may be viable alternatives depending on the nature of your needs. ChatGPT can be accessed via the Chat mode and is what we used for the examples below.
 

OpenAI Playground Tokens and Settings

De billing model for using this service is constructed around the concept of tokens. Each new user gets $18 of free credit (900K tokens) that can be used during their first 3 months from sign up; after that, it’s $0.02 for every 1,000 tokens.

There is a token counter in the footer of the Playground display which can help you keep track of how many tokens you are using. 1 token is approximately 4 characters (or 0.75 words), with token usage measured against both your prompts and the responses.

Se även  Marketers' secrets to overcoming challenges

You can limit the number of tokens that can be used in a response by toggling the Maximum length slider on the right hand sidebar, which is set to a 256-token cap by default. If you make an inquiry that requires an elaborate response, you may see the response get cut off before completion; in this case, it may be helpful to increase the Maximum length.

There is a maximum of 4,000 tokens that can be used in a single “request” (single session), i.e. a series of questions within the same Playground. Once you’ve hit that limit, all you need to do is delete your earlier prompt questions and answers, or save them as a “preset” before moving on to a new prompt.

open ai playground-skärmdump med pilmarkeringsknapp för att spara din förinställning

Notera: The use of tokens is required in the OpenAI Playground, but not when using ChatGPT natively. As of the time of this writing, ChatGPT is still free to use. A paid version of ChatGPT with advanced features and benefits is also available—ChatGPT Plus.
 

OpenAI Playground and ChatGPT Temperature

öppen ai lekplats skärmdump markering där du kan justera temperaturen

The Temperature setting controls randomness; lowering the temperature results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive. For most PPC purposes, we recommend a temperature range of 0.6-0.8 as optimal.
 

10 Ways PPC Marketers Can Use GPT to Improve Workflow Efficiency

 

“In terms of use cases, there are many different ways in which people working in all industries, and all fields of expertise, can lean on tools like ChatGPT and the OpenAI API to improve their efficiency and automate certain redundant tasks. This technology can help with smaller, repetitive tasks, such as breaking down a long document into a bullet point summary. However, when it comes to critical thinking and understanding the implications of things, I would be very cautious about over-relying on AI.”

Porträtt av Josh O'Donnell
Josh O'Donnell, Sr. Strategist, Paid Search at Tinuiti

A couple of important things to consider before diving into our examples below:

  1. ChatGPT/GPT language models training data cuts off in 2021. They do not have any knowledge of current events, and cannot accurately respond to questions about such topics. ChatGPT is not aware of things like who won the big game last night; it is not even aware of what day it is.
  2.  

  3. ChatGPT/GPT language models do not have access to the internet or any other kind of external data retrieval; they can only answer questions based on the knowledge acquired from their training data. They cannot verify facts or provide references, only generate responses based on their own internal knowledge and logic.

 

1. Keyword Research

Whether you work on the Paid Search side of marketing, or the organic side, you know how important (and time-consuming) thorough keyword research can be. One of the most important rules of marketing is to know your audience—which includes knowing what they want, and how they search for it—and the OpenAI Playground can help you find those answers faster.

Sample Scenario:

You’re just getting started building a new PPC campaign for a client that sells running shoes. To kick off your initial keyword research, you want to get an idea of which related keywords are being searched most often. You want a Top 20 keyword list, and GPT can generate a list for you to help you get started.

Se även  Getting started with the Agile Marketing Navigator: Building a marketing backlog

The prompt: Provide me with a list of 20 running shoe keywords for google ads, list them in descending order based on expected search volume in the United States.

The result:

skärmdump som visar hur open ai lekplats kan hjälpa till med sökordsforskning

Note that since OpenAI enables you to continue the “conversation” beyond your first query, we also asked it where it got the returned information from (above photo); it’s always important to consider the source when relying on AI-generated responses. This is a good example of why it’s important to take the outputs with a grain of salt, using them as inspiration to get you started, but not the finished product.
 

2. Competitor Research

Comprehensive competitor research and analysis is a crucial part of a marketer’s job, helping inform and guide their campaigns. However, just like keyword research, this is also an ongoing, time-consuming process.

When you work in a complex space—or your products or services are part of different spaces—it can sometimes feel overwhelming to assure you’re accounting for everything and everyone. The OpenAI Playground can help make short work of initial research in a variety of ways.

Below, we showcase the results provided by three different prompts aimed at unpacking competitor insights instantly…

Sample One: Ask for a list of top US competitors ranked largest to smallest with accompanying website URLs to get ideas for custom audiences, messaging, and product positioning.

skärmdump som visar resultaten när man frågar open ai-verktyget om en lista över de bästa löparskoföretagen i USA rankade störst till minst med webbadress

Sample Two: Ask objective questions about your competitor and their product.

skärmdump som visar resultat när man ber open ai playground att beskriva fördelarna med en konkurrentprodukt jämfört med en annan produkt, inklusive den som är mer inriktad på prismedvetna konsumenter

Sample Three: Ask about pain points for competitor products, and use that info to inform your own product messaging & marketing strategies.

exempel på att använda open ai för att avslöja konkurrentens smärtpunkter
 

3. Generate Ad Copy

In the below examples, we used the URL of the ad’s landing page to help inform the suggestions from ChatGPT, providing character limits in our prompt to help direct the output. If your original result doesn’t meet your expectations, continue to sculpt with additional follow-up prompts. GPT cannot access these web pages in real-time, but it can use the context from the URL structure to inform the output.

exempel på att använda open ai-lekplats för att hjälpa till med idéer om annonstexter

exempel på att använda open ai-lekplats för hjälp med att skriva beskrivningar av Google-annonser

“It’s more of a utilitarian thing, where you provide the tool with the data, and ask it to manipulate that data for a better output. One example is to provide it with a web page, and ask it to generate some ad copy based on the URL text; it can provide fifteen or twenty options within seconds. I would never recommend simply taking those headlines and pasting them into an ad, but you can now start off your project with a list that you or a teammate can garner inspiration from, and strategically refine or tweak to fully optimize. This gives the practitioner more time to spend on critical thinking, with ChatGPT taking away the more mundane elements of the task.”

Josh O'Donnell, Sr. Strategist, Paid Search at Tinuiti

The copy itself should be quality, but the important aspect of parity between what you’re saying on the ad and what’s on the page can be efficiently solved for.
 

4. Translations of Copy & Headlines

In the example below, we asked ChatGPT to translate the 5 English language ad copy options generated above into Spanish. Additional options currently available include French and Japanese translations.

Se även  How To Make Instagram Reels and Use Them to Your Advantage

exempel på användning av open ai-lekplats för kopieringsöversättning
 

5. Answer Questions on Demand

Similar to ChatGPT, the OpenAI Playground can also be used for Q&A purposes. Just remember that answers can only be generated based on the tool’s current knowledge.

skärmdump av Q&A-information från open ai-webbplatsen

Källa: https://platform.openai.com/examples/default-qa

This can be especially helpful during calls with clients when you need a fast and simple answer to keep the conversation moving forward.
 

6. Simplify Complex Concepts

When talking about digital marketing with other practitioners, we know our audience ‘speaks the same language’ and certain questions, concepts, or outcomes need no further explanation. However, those same complexities aren’t always as easy to communicate to newer team members or clients.

Even when our day-to-day contacts are digital savvy, they often have to convey information to those higher up the chain in their organization who might not be as familiar with the lingo, or even why certain things they’re highlighting matter.

For scenarios like these, OpenAI’s Summarize for a 2nd grader feature can prove especially helpful. Once you have the foundation laid out, you can add more color and context to paint the fuller picture without worrying the basics would be glazed over.
 

7. Generate Product Descriptions & Names

Working with accurate, well-optimized product names and descriptions is one of the most essential elements of effective marketing. Strong, descriptive names and product information help search engines and users alike in uncovering the items that will be most relevant to their needs.

skärmdump från open ai-webbplatsen som visar hur deras produktnamnsgenerator fungerar

Källa: https://platform.openai.com/examples/default-product-name-gen

While names and descriptions will always require a human touch for proper refinement, tools like ChatGPT and the OpenAI Playground can provide a great starting point to build from.
 

8. Parse Unstructured Data

The OpenAI Playground makes it easy to organize long-form text into a table format. Simply specify a desired structure, provide a few examples to work from, and enjoy the time saved.

skärmdump från open ai-webbplats som visar en uppmaning om att analysera ostrukturerad data

Källa: https://platform.openai.com/examples/default-parse-data

skärmdump från open ai-webbplats som visar ett svar från en uppmaning som ber om strukturerad data

Källa: https://platform.openai.com/examples/default-parse-data

 

9. Call Summaries & Follow-Ups

Call summaries are an important aspect of keeping organized and ensuring everyone working on a project is clued into plans and discussions, even if they weren’t part of the original calls. Putting together these comprehensive, valuable recaps can sometimes take as much time as the call itself, but GPT can help.

Below, we asked GPT to write a follow-up email based on a call summary.

skärmdump av svaret när du ber GPT att skriva uppföljningsmail baserat på samtalssammanfattning
 

10. Convert text from first-person to third-person

We have found this feature especially helpful for turning our own notes into actionable steps someone can follow when shared. For example, if you want to share steps for completing a process with a team member or client, you can type naturally using “I” language to convey those directions. You can then quickly convert the text to third-person, adjusting as necessary for optimal clarity.

Skärmdump från Open AI-webbplatsen som visar hur tredjepersonskonverterare fungerar

Källa: https://platform.openai.com/examples/default-third-person

 

Slutsats

 
The capabilities of advanced tools like OpenAI’s Playground and ChatGPT can make short work of mundane tasks, help quickly generate ideas and direction, and ultimately save us all time to focus on the elements of marketing and advertising where our expertise and strategic insights can truly shine. If you’re interested in more under-the-hood information about how ChatGPT works, check out Stephen Wolfram’s breakdown of ChatGPT. Also see here for additional application options, eller reach out today to learn more about how our Paid Search team kan ta dina PPC-annonseringsresultat till nästa nivå!
 

Källlänk

Håll ett öga på vad vi gör
Bli först med att få de senaste uppdateringarna och exklusivt innehåll direkt till din e-postinkorg.
Vi lovar att inte spamma dig. Du kan avbryta prenumerationen när som helst.
Ogiltig e-postadress

MARKNADSFÖRING

Mnemoniskt innehållsstrategiramverk kan väcka konversationer

Publicerad

Mnemoniskt innehållsstrategiramverk kan väcka konversationer

I’m a sucker for mnemonics.

In fact, I remember how to spell it by “Me Nomics Except M nOt N In Case Spelling.”

OK, that’s a lie. But I daresay ChatGPT could never come up with that.

Anyway, one of my favorite idea-remembering devices comes from my hero Philip Kotler. He reduces his perfect definition of marketing to CCDVTP – Create and Communicate Value to a Target at a Profit.”

I lean on that mnemonic device when anyone asks about the best definition of marketing’s function in a business.

However, what makes a great mnemonic like CCDVTP is that each word the letter represents has something deeper behind it. So it’s not just six words – it’s six operating concepts with definitions made easier to remember by just remembering how the six words go together.

A mnemonic device for content strategy

I’ve written about the standard framework for developing or strengthening your content strategy. It’s one of the core modules of a CMI University course. It can be a lot to take in because the framework’s concepts and definitions need to be explained in varying levels of detail.

So, recently, I created a mnemonic device to use in my explanation – the 5 Cs: Coordination och Collaboration produce Innehåll innan Containers and make Channels measurable.

5Cs of #ContentStrategy: Coordination and Collaboration produce Content before Containers and make Channels measurable via @Robert_Rose @CMIContent. Klicka för att tweeta

Se även  How Video Consumption is Changing in 2022 [New Research]

It works as a core or high-level definition of a content marketing strategy. But, like Kotler’s CCDVTP, it also lets me drill into the framework’s five concepts or pressure points. Let me explain:

Coordination

The primary purpose of a innehållsstrategi is to develop and manage core responsibilities and processes. In addition, they allow marketing to build and continually assess resource allocation, skill sets, and charters the marketing team needs to make content a företag strength.

Most businesses that lack this C struggle with content as a repeatable or measurable approach. As I’ve said, content is everyone’s job in many businesses and no one’s strategy. A key element of a content strategy is a focus on building coordination into how ideas become content and ultimately generate business value.

Most businesses that lack coordination struggle with making #content a repeatable and measurable approach, says @Robert_Rose. Klicka för att tweeta

Collaboration

In many businesses, content is developed in silos, especially with sales and marketing. Sometimes, it may be divided by channel – web, email, and sales teams don’t work together. In other cases, it may be by function – PR, sales, marketing, brand, and demand generation have different approaches.

Content is a team sport. The practitioners’ job is not to be good at content but to enable the business to be good at content. Scalability only happens through an effective, collaborative approach to transforming ideas into content and content into experiences.

Se även  Monique Battiste om laddning framåt

Content before containers

As marketers, you are trained to think container first and content second. You start with “I need a web page,” “I need an email,” or “I need a blog post.” Then, your next step is to create content specific to that container.

If you start with “I need a blog post” and then create the #content idea, you’re doing it wrong, says @Robert_Rose via @CMIContent. Klicka för att tweeta

I can’t tell you how many big ideas I’ve seen trapped in the context of a blog post simply because that was how it was conceived. I’ve also seen the reverse – small ideas spun into an e-book or white paper because someone wanted that digital asset.

This pressure point requires reverse thinking about your business’ process to create content. The first step must be to create fully formed ideas (big and small) and then (and only then) figure out which containers and how many might be appropriate.

My test to see whether marketing teams put content before containers is to look at their request or intake form. Does it say, “What kind of content do you need?” and list options, such as email, white paper, e-book, and brochure?  Or does it say, “Please explain the idea or story you’d like to develop more fully?”

Se även  Getting started with the Agile Marketing Navigator: Building a marketing backlog

Channels

I purposely put channels last because they express the kind of content you create. Channels dictate how you ultimately reach the customers and how the customers will access your content. Which or how many of your content channels do you treat as a media company would?

Is your corporate blog truly centered on the audience, or is it centered on your product or brand? Is it a repository where you put everything from news about your product and how to use it to what to expect in the future and how other customers use your product?

What about your social media, website, newsletters, and thought leadership center? What is their purpose and editorial strategy? How do you evolve your content products as your audience changes as a media company does? Without a clear strategy for every channel, the measurement of content becomes guesswork at best.

When you examine your strategic approach to content, I hope the 5Cs mnemonic device helps you have those necessary conversations around coordination, collaboration, content before containers, and channels with the stakeholders in your business.

Det är din historia. Berätta väl.

Prenumerera till arbetsdags- eller veckovisa CMI-e-postmeddelanden för att få Rose-Colored Glasses i din inkorg varje vecka. 

HANDPLOCKAT RELATERAT INNEHÅLL:

Omslagsbild av Joseph Kalinowski/Content Marketing Institute



Källlänk

Håll ett öga på vad vi gör
Bli först med att få de senaste uppdateringarna och exklusivt innehåll direkt till din e-postinkorg.
Vi lovar att inte spamma dig. Du kan avbryta prenumerationen när som helst.
Ogiltig e-postadress
Fortsätt läsa

MARKNADSFÖRING

Moz Links API: En introduktion

Publicerad

Moz Links API: En introduktion

What exactly IS an API? They’re those things that you copy and paste long strange codes into Screaming Frog for links data on a Site Crawl, right?

I’m here to tell you there’s so much more to them than that – if you’re willing to take just a few little steps. But first, some basics.

What’s an API?

API stands for “application programming interface”, and it’s just the way of… using a thing. Everything has an API. The web is a giant API that takes URLs as input and returns pages.

But special data services like the Moz Links API have their own set of rules. These rules vary from service to service and can be a major stumbling block for people taking the next step.

When Screaming Frog gives you the extra links columns in a crawl, it’s using the Moz Links API, but you can have this capability anywhere. For example, all that tedious manual stuff you do in spreadsheet environments can be automated from data-pull to formatting and emailing a report.

If you take this next step, you can be more efficient than your competitors, designing and delivering your own SEO services instead of relying upon, paying for, and being limited by the next proprietary product integration.

GET vs. POST

Most APIs you’ll encounter use the same data transport mechanism as the web. That means there’s a URL involved just like a website. Don’t get scared! It’s easier than you think. In many ways, using an API is just like using a website.

As with loading web pages, the request may be in one of two places: the URL itself, or in the body of the request. The URL is called the “endpoint” and the often invisibly submitted extra part of the request is called the “payload” or “data”. When the data is in the URL, it’s called a “query string” and indicates the “GET” method is used. You see this all the time when you search:

https://www.google.com/search?q=moz+links+api <-- GET method 

When the data of the request is hidden, it’s called a “POST” request. You see this when you submit a form on the web and the submitted data does not show on the URL. When you hit the back button after such a POST, browsers usually warn you against double-submits. The reason the POST method is often used is that you can fit a lot more in the request using the POST method than the GET method. URLs would get very long otherwise. The Moz Links API uses the POST method.

Making requests

A web browser is what traditionally makes requests of websites for web pages. The browser is a type of software known as a client. Clients are what make requests of services. More than just browsers can make requests. The ability to make client web requests is often built into programming languages like Python, or can be broken out as a standalone tool. The most popular tools for making requests outside a browser are curl och wget.

We are discussing Python here. Python has a built-in library called URLLIB, but it’s designed to handle so many different types of requests that it’s a bit of a pain to use. There are other libraries that are more specialized for making requests of APIs. The most popular for Python is called requests. It’s so popular that it’s used for almost every Python API tutorial you’ll find on the web. So I will use it too. This is what “hitting” the Moz Links API looks like:

response = requests.post(endpoint, data=json_string, auth=auth_tuple)

Given that everything was set up correctly (more on that soon), this will produce the following output:

{'next_token': 'JYkQVg4s9ak8iRBWDiz1qTyguYswnj035nqrQ1oIbW96IGJsb2dZgGzDeAM7Rw==',
 'results': [{'anchor_text': 'moz',
              'external_pages': 7162,
              'external_root_domains': 2026}]}

This is JSON data. It’s contained within the response object that was returned from the API. It’s not on the drive or in a file. It’s in memory. So long as it’s in memory, you can do stuff with it (often just saving it to a file).

Se även  Kan Bing Chat AI ta över Google Bard?

If you wanted to grab a piece of data within such a response, you could refer to it like this:

response['results'][0]['external_pages']

This says: “Give me the first item in the results list, and then give me the external_pages value from that item.” The result would be 7162.

NOTE: If you’re actually following along executing code, the above line won’t work alone. There’s a certain amount of setup we’ll do shortly, including installing the requests library and setting up a few variables. But this is the basic idea.

JSON

JSON stands for JavaScript Object Notation. It’s a way of representing data in a way that’s easy for humans to read and write. It’s also easy for computers to read and write. It’s a very common data format for APIs that has somewhat taken over the world since the older ways were too difficult for most people to use. Some people might call this part of the “restful” API movement, but the much more difficult XML format is also considered “restful” and everyone seems to have their own interpretation. Consequently, I find it best to just focus on JSON and how it gets in and out of Python.

Python dictionaries

I lied to you. I said that the data structure you were looking at above was JSON. Technically it’s really a Python dictionary or dict datatype object. It’s a special kind of object in Python that’s designed to hold key/value pairs. The keys are strings and the values can be any type of object. The keys are like the column names in a spreadsheet. The values are like the cells in the spreadsheet. In this way, you can think of a Python dict as a JSON object. For example here’s creating a dict in Python:

my_dict = {
    "name": "Mike",
    "age": 52,
    "city": "New York"
}

And here is the equivalent in JavaScript:

var my_json = {
    "name": "Mike",
    "age": 52,
    "city": "New York"
}

Pretty much the same thing, right? Look closely. Key-names and string values get double-quotes. Numbers don’t. These rules apply consistently between JSON and Python dicts. So as you might imagine, it’s easy for JSON data to flow in and out of Python. This is a great gift that has made modern API-work highly accessible to the beginner through a tool that has revolutionized the field of data science and is making inroads into marketing, Jupyter Notebooks.

Flattening data

But beware! As data flows between systems, it’s not uncommon for the data to subtly change. For example, the JSON data above might be converted to a string. Strings might look exactly like JSON, but they’re not. They’re just a bunch of characters. Sometimes you’ll hear it called “serializing”, or “flattening”. It’s a subtle point, but worth understanding as it will help with one of the largest stumbling blocks with the Moz Links (and most JSON) APIs.

Objects have APIs

Actual JSON eller dict objekt har sina egna små API:er för att komma åt data inuti dem. Möjligheten att använda dessa JSON och dict API:er försvinner när data plattas till en sträng, men den kommer att färdas mellan system lättare och när den kommer till andra änden kommer den att "deserialiseras" och API:t kommer tillbaka på det andra systemet.

Data flödar mellan system

Detta är konceptet med bärbar, interoperabel data. När det kallades Electronic Data Interchange (eller EDI) var det en väldigt stor sak. Sedan kom webben och sedan XML och sedan JSON och nu är det bara en normal del av att göra affärer.

Se även  This 44-Year-Old Earns 7 Figures/Year Writing Copy at Home

Om du är i Python och du vill konvertera en dict till en tillplattad JSON-sträng, gör du följande:

import json my_dict = { "name": "Mike", "age": 52, "city": "New York" } json_string = json.dumps(my_dict)

...som skulle producera följande utdata:

'{"name": "Mike", "age": 52, "city": "New York"}'

Detta ser nästan likadant ut som det ursprungliga diktatet, men om du tittar noga kan du se att enstaka citattecken används runt hela saken. En annan uppenbar skillnad är att du kan radbryta riktiga strukturerade data för läsbarhet utan negativ effekt. Du kan inte göra det så lätt med snören. Det är därför det presenteras allt på en rad i ovanstående utdrag.

Sådan strängande processer görs när data överförs mellan olika system eftersom de inte alltid är kompatibla. Normala textsträngar å andra sidan är kompatibla med nästan allt och kan enkelt skickas på webbförfrågningar. Sådana tillplattade strängar av JSON-data kallas ofta förfrågan.

Anatomi av en begäran

Återigen, här är exempelförfrågan vi gjorde ovan:

response = requests.post(endpoint, data=json_string, auth=auth_tuple)

Nu när du förstår vad variabelnamnet json_string säger dig om dess innehåll, borde du inte bli förvånad över att se att det är så här vi fyller i den variabeln:

 data_dict = { "target": "moz.com/blog", "scope": "page", "limit": 1 } json_string = json.dumps(data_dict)

…och innehållet i json_string ser ut så här:

'{"target": "moz.com/blog", "scope": "page", "limit": 1}'

Detta är en av mina viktigaste upptäckter när jag lär mig Moz Links API. Detta är gemensamt med otaliga andra API:er där ute, men gör mig upprörd varje gång eftersom det är så mycket bekvämare att arbeta med strukturerade dikter än tillplattade strängar. De flesta API:er förväntar sig dock att data är en sträng för portabilitet mellan system, så vi måste konvertera den i sista stund innan själva API-anropet inträffar.

Pythonic laddar och dumpar

Nu kanske du undrar i exemplet ovan, vad en dumpning gör mitt i koden. De json.dumps() funktionen kallas en "dumper" eftersom den tar ett Python-objekt och dumpar det i en sträng. De json.loads() funktionen kallas en "loader" eftersom den tar en sträng och laddar den i ett Python-objekt.

Anledningen till vad som verkar vara singular- och pluraloptioner är faktiskt binära och strängalternativ. Om din data är binär använder du json.load() och json.dump(). Om din data är en sträng använder du json.loads() och json.dumps(). S:et står för sträng. Att lämna s av betyder binär.

Låt ingen säga att Python är perfekt. Det är bara det att dess grova kanter inte är överdrivet stötande.

Uppdrag vs jämställdhet

För er som är helt nya inom Python eller programmering i allmänhet, det vi gör när vi träffar API kallas en uppgift. Resultatet av requests.post() tilldelas den namngivna variabeln svar.

response = requests.post(endpoint, data=json_string, auth=auth_tuple)

Vi använder tecknet = för att tilldela värdet på höger sida av ekvationen till variabeln på vänster sida av ekvationen. Variabeln svar är nu en referens till objektet som returnerades från API:et. Uppdrag skiljer sig från jämlikhet. De == tecken används för jämlikhet.

# Detta är tilldelning: a = 1 # a är nu lika med 1 # Detta är likhet: a == 1 # Sant, men förlitar sig på att ovanstående rad har exekveras

POST-metoden

respons = requests.post(endpoint, data=json_string, auth=auth_tuple)

De requests biblioteket har en funktion som kallas posta() det krävs 3 argument. Det första argumentet är URL:en för slutpunkten. Det andra argumentet är data som ska skickas till slutpunkten. Det tredje argumentet är autentiseringsinformationen som ska skickas till slutpunkten.

Se även  Unleashing the Power of Shopify: En guide för utvecklare

Nyckelordsparametrar och deras argument

Du kanske märker att några av argumenten till posta() funktion har namn. Namn sätts lika med värden med =-tecknet. Så här definieras Python-funktioner. Det första argumentet är positionellt både för att det kommer först och även för att det inte finns något nyckelord. Nyckelordnade argument kommer efter positionsberoende argument. Tro mig, allt känns vettigt efter ett tag. Vi börjar alla tänka som Guido van Rossum.

def arbitrary_function(argument1, namn=argument2): # gör saker

Namnet i exemplet ovan kallas ett "sökord" och värdena som kommer in på dessa platser kallas "argument". Nu tilldelas argument till variabelnamn direkt i funktionsdefinitionen, så du kan referera till antingen argument1 eller argument2 var som helst i den här funktionen. Om du vill lära dig mer om reglerna för Python-funktioner kan du läsa om dem här.

Ställer in begäran

Okej, så låt oss låta dig göra allt som behövs för det framgång säkerställd ögonblick. Vi har visat den grundläggande begäran:

response = requests.post(endpoint, data=json_string, auth=auth_tuple)

…men vi har inte visat allt som ingår i det. Låt oss göra det nu. Om du följer med och inte har förfrågningsbiblioteket installerat kan du göra det med följande kommando från samma terminalmiljö som du kör Python från:

pip-installationsförfrågningar

Ofta har Jupyter redan förfrågningsbiblioteket installerat, men om det inte gör det kan du installera det med följande kommando inifrån en Notebook-cell:

!pip installationsförfrågningar

Och nu kan vi sätta ihop allt. Det finns bara några få saker här som är nya. Det viktigaste är hur vi tar 2 olika variabler och kombinerar dem till en enda variabel som kallas AUTH_TUPLE. Du måste skaffa din egen ACCESSID och SECRETKEY från Moz.com webbplats.

API:n förväntar sig att dessa två värden ska skickas som en Python-datastruktur som kallas a tupel. En tupel är en lista över värden som inte ändras. Det tycker jag är intressant requests.post() förväntar sig tillplattade strängar för data parameter, men förväntar sig en tupel för auth parameter. Jag antar att det är vettigt, men det här är de subtila sakerna att förstå när man arbetar med API:er.

Här är hela koden:

import json import pprint importförfrågningar # Set Constants ACCESSID = "mozscape-1234567890" # Ersätt med ditt åtkomst-ID SECRETKEY = "1234567890abcdef1234567890abcdef" # Ersätt med din hemliga nyckel Variables endpoint = "https:// lsapi.seomoz.com/v2/anchor_text" data_dict = {"target": "moz.com/blog", "scope": "page", "limit": 1} json_string = json.dumps(data_dict) # Gör Request response = requests.post(endpoint, data=json_string, auth=AUTH_TUPLE) # Skriv ut svaret pprint(response.json())

…som ger ut:

{'next_token': 'JYkQVg4s9ak8iRBWDiz1qTyguYswnj035nqrQ1oIbW96IGJsb2dZgGzDeAM7Rw==',
 'results': [{'anchor_text': 'moz',
              'external_pages': 7162,
              'external_root_domains': 2026}]}

Använder alla versaler för AUTH_TUPLE variabel är en konvention många använder i Python för att indikera att variabeln är en konstant. Det är inget krav, men det är en bra idé att följa konventioner när du kan.

Du kanske märker att jag inte använde alla versaler för slutpunkt variabel. Det är för att anchor_text endpoint är inte en konstant. Det finns ett antal olika slutpunkter som kan ta dess plats beroende på vilken typ av uppslag vi ville göra. Valen är:

  1. anchor_text

  2. final_redirect

  3. globala_toppsidor

  4. globala_top_root_domains

  5. index_metadata

  6. länk_korsning

  7. länk_status

  8. länkande_rotdomäner

  9. länkar

  10. top_pages

  11. url_metrics

  12. användningsdata

Och det leder till Jupyter Notebook som jag förberedde om detta ämne här på Github. Med den här anteckningsboken kan du utöka exemplet jag gav här till någon av de 12 tillgängliga slutpunkterna för att skapa en mängd användbara resultat, som kommer att bli föremål för artiklar som följer.

Källlänk

Håll ett öga på vad vi gör
Bli först med att få de senaste uppdateringarna och exklusivt innehåll direkt till din e-postinkorg.
Vi lovar att inte spamma dig. Du kan avbryta prenumerationen när som helst.
Ogiltig e-postadress
Fortsätt läsa

MARKNADSFÖRING

Vad företag får fel om innehållsmarknadsföring 2023 [Experttips]

Publicerad

Vad företag får fel om innehållsmarknadsföring 2023 [Experttips]

Löftet om inkommande marknadsföring är ett lockande som lockar företag av alla slag, men få förstår de ansträngningar som krävs för att bli framgångsrika. Efter några blogginlägg flammar de ut och klagar "Vi försökte innehållsmarknadsföring, men det fungerade inte riktigt för oss." Jag hör detta från potentiella kunder hela tiden.

(mer …)

Se även  How To Make Instagram Reels and Use Them to Your Advantage
Håll ett öga på vad vi gör
Bli först med att få de senaste uppdateringarna och exklusivt innehåll direkt till din e-postinkorg.
Vi lovar att inte spamma dig. Du kan avbryta prenumerationen när som helst.
Ogiltig e-postadress
Fortsätt läsa

Trendigt

sv_SESvenska