Skip to content

Instantly share code, notes, and snippets.

@mikejs
Created July 7, 2010 20:34
Show Gist options
  • Save mikejs/467234 to your computer and use it in GitHub Desktop.
Save mikejs/467234 to your computer and use it in GitHub Desktop.
# Replace all of the lxml cssselect calls in a python script with
# equivalent xpath calls.
import re
import sys
import lxml.cssselect
def cssselect_replace(match):
xpath = lxml.cssselect.css_to_xpath(match.group(2))
xpath = xpath.replace("'", "\\'").replace('"', '\\"')
return ".xpath(%s%s%s)" % (match.group(1), xpath, match.group(1))
if __name__ == '__main__':
try:
filename = sys.argv[1]
except IndexError:
print "enter a file to convert"
sys.exit(1)
with open(filename) as f:
text = f.read()
text = re.sub(r"\.cssselect\((['\"])([^\)]*)\1\)",
cssselect_replace, text)
with open(filename.replace('.py', '.py.better'), 'w') as w:
w.write(text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment