Currently, I can send the user-agent from playwright as well the viewport sizes. But i want to send all the headers informations like accept, accept_encoding, accept_language,referer, cookies,etc
. I looked about setExtraHTTPHeaders()
too. Is there any way to send them in playwright python.
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
context = browser.new_context(
user_agent=agent #agent declared above,
)
page = context.new_page()
response = page.goto("https://www.somewebsite.com/")
#Doing some work in the website
page.locator('#some_id').fill("some_text")
page.press('#another_id', "Enter")
page.route("**/*", intercept_route)
CodePudding user response:
Yes, it is possible to send additional headers using the setExtraHTTPHeaders
method in Playwright for Python. This method takes a dictionary as an argument, where the keys are the header names and the values are the corresponding header values.
For example, to set the Accept
, Accept-Encoding
, and Accept-Language
headers, you can use the following code:
headers = {'Accept': 'text/html,application/xhtml xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.5'}
context.setExtraHTTPHeaders(headers)
You can also add referer and cookies using the headers
headers = {'Referer': 'https://example.com',
'Cookie': 'session_id=abc123; user_id=123456'}
context.setExtraHTTPHeaders(headers)
CodePudding user response:
I apologize for the confusion, setExtraHTTPHeaders
is not a method of the BrowserContext
object in Playwright. This method is used in the JavaScript version of Playwright.
In python version of Playwright, you can use headers
attribute of Page
object to set headers before navigation.
page = await context.newPage()
await page.setExtraHTTPHeaders(headers)
await page.goto("https://example.com")
You can also use network.setExtraHTTPHeaders
method to set headers for all requests
await page.context.network.setRequestInterception(True)
page.on('request', request => {
request.headers = headers
request.continue_()
})