NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

Web scraping

Can XPath be used in Beautiful Soup?

Not directly. Beautiful Soup searches with its own methods and CSS selectors, so for XPath you parse the same HTML with lxml, which Beautiful Soup often uses underneath anyway.

The direct answer

Beautiful Soup has no XPath support. Its search tools are find, find_all and select, the last of which takes CSS selectors. If you want XPath, parse the HTML with lxml, which offers .xpath() on every element. You can use both in one script: Beautiful Soup for forgiving navigation, lxml for the queries XPath expresses better.

Option one: translate the XPath to CSS

Most XPath expressions used in scraping have a CSS equivalent, and select handles them well.

XPathCSS for select()
//div[@class="price"]div.price
//ul[@id="menu"]/liul#menu > li
//a[starts-with(@href, "/item/")]a[href^="/item/"]
//table//tr[2]/tdtable tr:nth-of-type(2) > td
//input[@type="hidden"]input[type=hidden]

The CSS selector entry explains the syntax in more depth.

Option two: use lxml for XPath

Things CSS cannot do well, such as matching by text content or stepping to a parent, are natural in XPath. Parse with lxml and query directly:

import lxml.html

tree = lxml.html.fromstring(page_source)
# the cell to the right of the label "Weight"
weight = tree.xpath('//th[normalize-space()="Weight"]/following-sibling::td[1]/text()')
# the product card that contains a "Sold out" badge
cards = tree.xpath('//span[contains(., "Sold out")]/ancestor::article')
print(weight[:1], len(cards))

Mixing both in one script

If most of your code already uses Beautiful Soup, convert a fragment to a string and hand it to lxml only where XPath helps:

import bs4
from lxml import etree

soup = bs4.BeautifulSoup(page_source, "lxml")
spec_block = soup.select_one("section.specs")
fragment = etree.HTML(str(spec_block))
rows = fragment.xpath('//tr[td[1][contains(., "Battery")]]/td[2]/text()')

The cost is a second parse of that fragment, which is negligible for normal page sizes.

Beautiful Soup ways to do XPath-like things

  • Text matching: soup.find("th", string="Weight") finds the label; then .find_next_sibling("td") steps across.
  • Parents: tag.find_parent("article") walks up the tree.
  • Regular expressions: pass re.compile(...) as an attribute value or as string=.

These are often enough, and they keep the code in one library.

Mistakes to avoid

Copying an XPath from the browser's developer tools gives a long absolute path such as /html/body/div[3]/div[2]/span. It breaks the moment the layout shifts. Write short, meaningful paths anchored on ids, classes or labels instead. Also remember that the browser shows the page after JavaScript ran; if your HTTP client receives a different document, no selector will find content that only appears after scripts. The page on static or dynamic pages explains how to tell.

Which to choose

For new code, pick by the queries you need. Many projects use CSS for ninety percent of fields and a couple of XPath expressions for the awkward ones. If you need a full framework with both built in, Scrapy selectors accept CSS and XPath side by side; the comparison of Scrapy and Beautiful Soup weighs the trade-offs.

Testing selectors before you rely on them

Whichever syntax you use, test selectors against saved copies of real pages, not only the one page you looked at. Save five or ten pages of each type to disk, run every selector against all of them, and print which ones return nothing. Product pages without a discount, listings with a single image, and pages in another language tend to break selectors written against the typical case. A tiny test like this, rerun after each layout change, catches most parser breakage before it reaches your data.

Common questions

Does Beautiful Soup use lxml internally?

It can. Passing "lxml" as the parser uses lxml to build the tree, but the search methods are still Beautiful Soup's own.

Is there a plugin that adds XPath to Beautiful Soup?

Not in the core library. The practical route is to query with lxml for those cases.

Is CSS or XPath faster?

For typical pages the difference is small; parsing the document usually costs more than the query.

Can XPath select text nodes?

Yes. Ending a path with /text() returns the text itself, which CSS selectors cannot do.

Why does my browser XPath return nothing in Python?

The browser may show content added by JavaScript, or a tbody the raw HTML lacks; check the HTML your client received.

Keep reading